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
unknown
date_merged
unknown
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
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Features/Core/Portable/AddParameter/IAddParameterService.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.AddParameter { internal interface IAddParameterService { /// <summary> /// Checks if there are indications that there might be more than one declarations that need to be fixed. /// The check does not look-up if there are other declarations (this is done later in the CodeAction). /// </summary> bool HasCascadingDeclarations(IMethodSymbol method); /// <summary> /// Adds a parameter to a method. /// </summary> /// <param name="newParameterIndex"><see langword="null"/> to add as the final parameter</param> /// <returns></returns> Task<Solution> AddParameterAsync( Document invocationDocument, IMethodSymbol method, ITypeSymbol newParamaterType, RefKind refKind, string parameterName, int? newParameterIndex, bool fixAllReferences, 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.AddParameter { internal interface IAddParameterService { /// <summary> /// Checks if there are indications that there might be more than one declarations that need to be fixed. /// The check does not look-up if there are other declarations (this is done later in the CodeAction). /// </summary> bool HasCascadingDeclarations(IMethodSymbol method); /// <summary> /// Adds a parameter to a method. /// </summary> /// <param name="newParameterIndex"><see langword="null"/> to add as the final parameter</param> /// <returns></returns> Task<Solution> AddParameterAsync( Document invocationDocument, IMethodSymbol method, ITypeSymbol newParamaterType, RefKind refKind, string parameterName, int? newParameterIndex, bool fixAllReferences, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/IAssemblySymbolExtensions.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.Shared.Extensions { internal static class IAssemblySymbolExtensions { private const string AttributeSuffix = "Attribute"; public static bool ContainsNamespaceName( this List<IAssemblySymbol> assemblies, string namespaceName) { // PERF: Expansion of "assemblies.Any(a => a.NamespaceNames.Contains(namespaceName))" // to avoid allocating a lambda. foreach (var a in assemblies) { if (a.NamespaceNames.Contains(namespaceName)) { return true; } } return false; } public static bool ContainsTypeName(this List<IAssemblySymbol> assemblies, string typeName, bool tryWithAttributeSuffix = false) { if (!tryWithAttributeSuffix) { // PERF: Expansion of "assemblies.Any(a => a.TypeNames.Contains(typeName))" // to avoid allocating a lambda. foreach (var a in assemblies) { if (a.TypeNames.Contains(typeName)) { return true; } } } else { var attributeName = typeName + AttributeSuffix; foreach (var a in assemblies) { var typeNames = a.TypeNames; if (typeNames.Contains(typeName) || typeNames.Contains(attributeName)) { return true; } } } return false; } public static bool IsSameAssemblyOrHasFriendAccessTo(this IAssemblySymbol assembly, IAssemblySymbol toAssembly) { return Equals(assembly, toAssembly) || (assembly.IsInteractive && toAssembly.IsInteractive) || toAssembly.GivesAccessTo(assembly); } } }
// 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.Shared.Extensions { internal static class IAssemblySymbolExtensions { private const string AttributeSuffix = "Attribute"; public static bool ContainsNamespaceName( this List<IAssemblySymbol> assemblies, string namespaceName) { // PERF: Expansion of "assemblies.Any(a => a.NamespaceNames.Contains(namespaceName))" // to avoid allocating a lambda. foreach (var a in assemblies) { if (a.NamespaceNames.Contains(namespaceName)) { return true; } } return false; } public static bool ContainsTypeName(this List<IAssemblySymbol> assemblies, string typeName, bool tryWithAttributeSuffix = false) { if (!tryWithAttributeSuffix) { // PERF: Expansion of "assemblies.Any(a => a.TypeNames.Contains(typeName))" // to avoid allocating a lambda. foreach (var a in assemblies) { if (a.TypeNames.Contains(typeName)) { return true; } } } else { var attributeName = typeName + AttributeSuffix; foreach (var a in assemblies) { var typeNames = a.TypeNames; if (typeNames.Contains(typeName) || typeNames.Contains(attributeName)) { return true; } } } return false; } public static bool IsSameAssemblyOrHasFriendAccessTo(this IAssemblySymbol assembly, IAssemblySymbol toAssembly) { return Equals(assembly, toAssembly) || (assembly.IsInteractive && toAssembly.IsInteractive) || toAssembly.GivesAccessTo(assembly); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/VisualStudio/IntegrationTest/IntegrationTests/AbstractInteractiveWindowTest.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.VisualStudio.IntegrationTest.Utilities; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests { public abstract class AbstractInteractiveWindowTest : AbstractIntegrationTest { protected AbstractInteractiveWindowTest(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); ClearInteractiveWindow(); } protected void ClearInteractiveWindow() { VisualStudio.InteractiveWindow.Initialize(); VisualStudio.InteractiveWindow.ClearScreen(); VisualStudio.InteractiveWindow.ShowWindow(); VisualStudio.InteractiveWindow.Reset(); } } }
// 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.VisualStudio.IntegrationTest.Utilities; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests { public abstract class AbstractInteractiveWindowTest : AbstractIntegrationTest { protected AbstractInteractiveWindowTest(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); ClearInteractiveWindow(); } protected void ClearInteractiveWindow() { VisualStudio.InteractiveWindow.Initialize(); VisualStudio.InteractiveWindow.ClearScreen(); VisualStudio.InteractiveWindow.ShowWindow(); VisualStudio.InteractiveWindow.Reset(); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/VisualStudio/LiveShare/Impl/Client/Projects/IRemoteProjectInfoProvider.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; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { internal interface IRemoteProjectInfoProvider { Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(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.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { internal interface IRemoteProjectInfoProvider { Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/Syntax/GreenNodeExtensions.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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal static class GreenNodeExtensions { public static TNode WithAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation> annotations) where TNode : GreenNode { var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); foreach (var candidate in annotations) { if (!newAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } if (newAnnotations.Count == 0) { newAnnotations.Free(); var existingAnnotations = node.GetAnnotations(); if (existingAnnotations == null || existingAnnotations.Length == 0) { return node; } else { return (TNode)node.SetAnnotations(null); } } else { return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } } public static TNode WithAdditionalAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation>? annotations) where TNode : GreenNode { var existingAnnotations = node.GetAnnotations(); if (annotations == null) { return node; } var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); newAnnotations.AddRange(existingAnnotations); foreach (var candidate in annotations) { if (!newAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } if (newAnnotations.Count == existingAnnotations.Length) { newAnnotations.Free(); return node; } else { return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } } public static TNode WithoutAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation>? annotations) where TNode : GreenNode { var existingAnnotations = node.GetAnnotations(); if (annotations == null || existingAnnotations.Length == 0) { return node; } var removalAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); removalAnnotations.AddRange(annotations); try { if (removalAnnotations.Count == 0) { return node; } var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); foreach (var candidate in existingAnnotations) { if (!removalAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } finally { removalAnnotations.Free(); } } public static TNode WithDiagnosticsGreen<TNode>(this TNode node, DiagnosticInfo[]? diagnostics) where TNode : GreenNode { return (TNode)node.SetDiagnostics(diagnostics); } public static TNode WithoutDiagnosticsGreen<TNode>(this TNode node) where TNode : GreenNode { var current = node.GetDiagnostics(); if (current == null || current.Length == 0) { return node; } return (TNode)node.SetDiagnostics(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 System.Linq; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal static class GreenNodeExtensions { public static TNode WithAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation> annotations) where TNode : GreenNode { var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); foreach (var candidate in annotations) { if (!newAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } if (newAnnotations.Count == 0) { newAnnotations.Free(); var existingAnnotations = node.GetAnnotations(); if (existingAnnotations == null || existingAnnotations.Length == 0) { return node; } else { return (TNode)node.SetAnnotations(null); } } else { return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } } public static TNode WithAdditionalAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation>? annotations) where TNode : GreenNode { var existingAnnotations = node.GetAnnotations(); if (annotations == null) { return node; } var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); newAnnotations.AddRange(existingAnnotations); foreach (var candidate in annotations) { if (!newAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } if (newAnnotations.Count == existingAnnotations.Length) { newAnnotations.Free(); return node; } else { return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } } public static TNode WithoutAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation>? annotations) where TNode : GreenNode { var existingAnnotations = node.GetAnnotations(); if (annotations == null || existingAnnotations.Length == 0) { return node; } var removalAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); removalAnnotations.AddRange(annotations); try { if (removalAnnotations.Count == 0) { return node; } var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); foreach (var candidate in existingAnnotations) { if (!removalAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } finally { removalAnnotations.Free(); } } public static TNode WithDiagnosticsGreen<TNode>(this TNode node, DiagnosticInfo[]? diagnostics) where TNode : GreenNode { return (TNode)node.SetDiagnostics(diagnostics); } public static TNode WithoutDiagnosticsGreen<TNode>(this TNode node) where TNode : GreenNode { var current = node.GetDiagnostics(); if (current == null || current.Length == 0) { return node; } return (TNode)node.SetDiagnostics(null); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Analyzers/Core/Analyzers/UseCompoundAssignment/UseCompoundAssignmentUtilities.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 System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseCompoundAssignment { internal static class UseCompoundAssignmentUtilities { internal const string Increment = nameof(Increment); internal const string Decrement = nameof(Decrement); public static void GenerateMaps<TSyntaxKind>( ImmutableArray<(TSyntaxKind exprKind, TSyntaxKind assignmentKind, TSyntaxKind tokenKind)> kinds, out ImmutableDictionary<TSyntaxKind, TSyntaxKind> binaryToAssignmentMap, out ImmutableDictionary<TSyntaxKind, TSyntaxKind> assignmentToTokenMap) where TSyntaxKind : struct { var binaryToAssignmentBuilder = ImmutableDictionary.CreateBuilder<TSyntaxKind, TSyntaxKind>(); var assignmentToTokenBuilder = ImmutableDictionary.CreateBuilder<TSyntaxKind, TSyntaxKind>(); foreach (var (exprKind, assignmentKind, tokenKind) in kinds) { binaryToAssignmentBuilder[exprKind] = assignmentKind; assignmentToTokenBuilder[assignmentKind] = tokenKind; } binaryToAssignmentMap = binaryToAssignmentBuilder.ToImmutable(); assignmentToTokenMap = assignmentToTokenBuilder.ToImmutable(); Debug.Assert(binaryToAssignmentMap.Count == assignmentToTokenMap.Count); Debug.Assert(binaryToAssignmentMap.Values.All(assignmentToTokenMap.ContainsKey)); } public static bool IsSideEffectFree( ISyntaxFacts syntaxFacts, SyntaxNode expr, SemanticModel semanticModel, CancellationToken cancellationToken) { return IsSideEffectFreeRecurse(syntaxFacts, expr, semanticModel, isTopLevel: true, cancellationToken); } private static bool IsSideEffectFreeRecurse( ISyntaxFacts syntaxFacts, SyntaxNode expr, SemanticModel semanticModel, bool isTopLevel, CancellationToken cancellationToken) { if (expr == null) { return false; } // it basically has to be of the form "a.b.c", where all components are locals, // parameters or fields. Basically, nothing that can cause arbitrary user code // execution when being evaluated by the compiler. if (syntaxFacts.IsThisExpression(expr) || syntaxFacts.IsBaseExpression(expr)) { // Referencing this/base like this.a.b.c causes no side effects itself. return true; } if (syntaxFacts.IsIdentifierName(expr)) { return IsSideEffectFreeSymbol(expr, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsParenthesizedExpression(expr)) { syntaxFacts.GetPartsOfParenthesizedExpression(expr, out _, out var expression, out _); return IsSideEffectFreeRecurse(syntaxFacts, expression, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsSimpleMemberAccessExpression(expr)) { syntaxFacts.GetPartsOfMemberAccessExpression(expr, out var subExpr, out _); return IsSideEffectFreeRecurse(syntaxFacts, subExpr, semanticModel, isTopLevel: false, cancellationToken) && IsSideEffectFreeSymbol(expr, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsConditionalAccessExpression(expr)) { syntaxFacts.GetPartsOfConditionalAccessExpression(expr, out var expression, out var whenNotNull); return IsSideEffectFreeRecurse(syntaxFacts, expression, semanticModel, isTopLevel: false, cancellationToken) && IsSideEffectFreeRecurse(syntaxFacts, whenNotNull, semanticModel, isTopLevel: false, cancellationToken); } // Something we don't explicitly handle. Assume this may have side effects. return false; } private static bool IsSideEffectFreeSymbol( SyntaxNode expr, SemanticModel semanticModel, bool isTopLevel, CancellationToken cancellationToken) { var symbolInfo = semanticModel.GetSymbolInfo(expr, cancellationToken); if (symbolInfo.CandidateSymbols.Length > 0 || symbolInfo.Symbol == null) { // couldn't bind successfully, assume that this might have side-effects. return false; } var symbol = symbolInfo.Symbol; switch (symbol.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: case SymbolKind.Field: case SymbolKind.Parameter: case SymbolKind.Local: return true; } if (symbol.Kind == SymbolKind.Property && isTopLevel) { // If we have `this.Prop = this.Prop * 2`, then that's just a single read/write of // the prop and we can safely make that `this.Prop *= 2` (since it will still be a // single read/write). However, if we had `this.prop.x = this.prop.x * 2`, then // that's multiple reads of `this.prop`, and it's not safe to convert that to // `this.prop.x *= 2` in the case where calling 'prop' may have side effects. // // Note, this doesn't apply if the property is a ref-property. In that case, we'd // go from a read and a write to to just a read (and a write to it's returned ref // value). var property = (IPropertySymbol)symbol; if (property.RefKind == RefKind.None) { return true; } } 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.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseCompoundAssignment { internal static class UseCompoundAssignmentUtilities { internal const string Increment = nameof(Increment); internal const string Decrement = nameof(Decrement); public static void GenerateMaps<TSyntaxKind>( ImmutableArray<(TSyntaxKind exprKind, TSyntaxKind assignmentKind, TSyntaxKind tokenKind)> kinds, out ImmutableDictionary<TSyntaxKind, TSyntaxKind> binaryToAssignmentMap, out ImmutableDictionary<TSyntaxKind, TSyntaxKind> assignmentToTokenMap) where TSyntaxKind : struct { var binaryToAssignmentBuilder = ImmutableDictionary.CreateBuilder<TSyntaxKind, TSyntaxKind>(); var assignmentToTokenBuilder = ImmutableDictionary.CreateBuilder<TSyntaxKind, TSyntaxKind>(); foreach (var (exprKind, assignmentKind, tokenKind) in kinds) { binaryToAssignmentBuilder[exprKind] = assignmentKind; assignmentToTokenBuilder[assignmentKind] = tokenKind; } binaryToAssignmentMap = binaryToAssignmentBuilder.ToImmutable(); assignmentToTokenMap = assignmentToTokenBuilder.ToImmutable(); Debug.Assert(binaryToAssignmentMap.Count == assignmentToTokenMap.Count); Debug.Assert(binaryToAssignmentMap.Values.All(assignmentToTokenMap.ContainsKey)); } public static bool IsSideEffectFree( ISyntaxFacts syntaxFacts, SyntaxNode expr, SemanticModel semanticModel, CancellationToken cancellationToken) { return IsSideEffectFreeRecurse(syntaxFacts, expr, semanticModel, isTopLevel: true, cancellationToken); } private static bool IsSideEffectFreeRecurse( ISyntaxFacts syntaxFacts, SyntaxNode expr, SemanticModel semanticModel, bool isTopLevel, CancellationToken cancellationToken) { if (expr == null) { return false; } // it basically has to be of the form "a.b.c", where all components are locals, // parameters or fields. Basically, nothing that can cause arbitrary user code // execution when being evaluated by the compiler. if (syntaxFacts.IsThisExpression(expr) || syntaxFacts.IsBaseExpression(expr)) { // Referencing this/base like this.a.b.c causes no side effects itself. return true; } if (syntaxFacts.IsIdentifierName(expr)) { return IsSideEffectFreeSymbol(expr, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsParenthesizedExpression(expr)) { syntaxFacts.GetPartsOfParenthesizedExpression(expr, out _, out var expression, out _); return IsSideEffectFreeRecurse(syntaxFacts, expression, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsSimpleMemberAccessExpression(expr)) { syntaxFacts.GetPartsOfMemberAccessExpression(expr, out var subExpr, out _); return IsSideEffectFreeRecurse(syntaxFacts, subExpr, semanticModel, isTopLevel: false, cancellationToken) && IsSideEffectFreeSymbol(expr, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsConditionalAccessExpression(expr)) { syntaxFacts.GetPartsOfConditionalAccessExpression(expr, out var expression, out var whenNotNull); return IsSideEffectFreeRecurse(syntaxFacts, expression, semanticModel, isTopLevel: false, cancellationToken) && IsSideEffectFreeRecurse(syntaxFacts, whenNotNull, semanticModel, isTopLevel: false, cancellationToken); } // Something we don't explicitly handle. Assume this may have side effects. return false; } private static bool IsSideEffectFreeSymbol( SyntaxNode expr, SemanticModel semanticModel, bool isTopLevel, CancellationToken cancellationToken) { var symbolInfo = semanticModel.GetSymbolInfo(expr, cancellationToken); if (symbolInfo.CandidateSymbols.Length > 0 || symbolInfo.Symbol == null) { // couldn't bind successfully, assume that this might have side-effects. return false; } var symbol = symbolInfo.Symbol; switch (symbol.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: case SymbolKind.Field: case SymbolKind.Parameter: case SymbolKind.Local: return true; } if (symbol.Kind == SymbolKind.Property && isTopLevel) { // If we have `this.Prop = this.Prop * 2`, then that's just a single read/write of // the prop and we can safely make that `this.Prop *= 2` (since it will still be a // single read/write). However, if we had `this.prop.x = this.prop.x * 2`, then // that's multiple reads of `this.prop`, and it's not safe to convert that to // `this.prop.x *= 2` in the case where calling 'prop' may have side effects. // // Note, this doesn't apply if the property is a ref-property. In that case, we'd // go from a read and a write to to just a read (and a write to it's returned ref // value). var property = (IPropertySymbol)symbol; if (property.RefKind == RefKind.None) { return true; } } return false; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Test/Syntax/Parsing/ParserRegressionTests.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 Roslyn.Test.Utilities.Syntax; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { public class ParserRegressionTests : ParsingTests { public ParserRegressionTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options ?? TestOptions.Regular); } [Fact] public void PartialLocationInModifierList() { var comp = CreateCompilation(@" class Program { partial abstract class A {} partial abstract class A {} partial partial class B {} partial partial class B {} partial abstract struct S {} partial abstract struct S {} }"); comp.VerifyDiagnostics( // (4,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial abstract class A {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(4, 5), // (5,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial abstract class A {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(5, 5), // (7,13): error CS1525: Invalid expression term 'partial' // partial partial class B {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(7, 13), // (7,13): error CS1002: ; expected // partial partial class B {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(7, 13), // (8,13): error CS1525: Invalid expression term 'partial' // partial partial class B {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(8, 13), // (8,13): error CS1002: ; expected // partial partial class B {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(8, 13), // (10,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial abstract struct S {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(10, 5), // (11,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial abstract struct S {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(11, 5), // (10,29): error CS0106: The modifier 'abstract' is not valid for this item // partial abstract struct S {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "S").WithArguments("abstract").WithLocation(10, 29), // (8,13): error CS0102: The type 'Program' already contains a definition for '' // partial partial class B {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("Program", "").WithLocation(8, 13), // (8,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // partial partial class B {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(8, 5), // (7,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // partial partial class B {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(7, 5)); } [WorkItem(540005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540005")] [Fact] public void c01() { var test = @"/// \u2750\uDFC1 = </ @goto </ ascending abstract + ( descending __arglist + descending @if <? @switch + global @long + @orderby \u23DC\u6D71\u5070\u9350 ++ into _\u6105\uE331\u27D0 # join [ + break @extern [ @char << partial | + remove + do @else + @typeof @private + "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540006")] [Fact] public void c02() { var test = @"internal int TYPES() { break retVal = @while ; __reftype CLASS c = dynamic descending CLASS( % ; on IF xx = module _4䓞 |= \u14DB\u0849 <![CDATA[ c => @default $ retVal @assembly += c void .Member & -= ; @typeof "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")] [Fact] public void c03() { var test = @"/// </summary> /// <returns></returns> else int OPERATOR @uint $ ) { - static ? operator :: ] @readonly = @on async int? , [ return ] { 1 ! , @property & 3 ! @case % partial += ;/*[] bug*/ // YES [] int % ] endregion var = ]]> @for |= @struct , 3, lock 4 @on % 5 goto } @stackalloc } /*,;*/ int %= i = @fixed ?> int << a base <= 1] default ; "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")] [Fact] public void c04() { var test = @"/// </summary> /// <returns></returns> internal do OPERATOR || ) { int?[] a = new int? \u14DB\u0849 [5] { 1, 2, 3, 4, @using } /= /*[] bug*/ // YES [] int[] var = { 1, 2, 3, 4, 5 } $ /*,;*/ int i = ; int)a[1];/*[]*/ i = i <<= @__arglist - i @sbyte * @extern / i % i ++ % i || @checked ^ i; /*+ - * / % & | ^*/ "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")] [Fact] public void c000138() { var test = @"int?[] /// a = new int? . @string ] { 1, typeof $ 3, 4, 5 } static ; @partial /*[] bug*/ // YES [] int[] var = { 1, else , 3 </ 4 | 5 };/*,;*/ int i = (int)a @in [ __refvalue ] [ /*[]*/ @readonly = i + i - abstract @typevar * i / @this % i & , i | i ^ unchecked i; in /*+ - * / % & | ^*/ bool b = true & false + | true ^ false readonly ;/*& | ^*/ @unsafe = !b;/*!*/ i = ~i;/*~i*/ b = i < (i - 1 @for ) && (i + 1) > i;/*< && >*/ "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")] [Fact] public void c000241() { var test = @"/// </summary> /// <returns></returns> const by TYPES ascending / ) $ { @let int @byte @by | 0 ; "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")] [Fact] public void c024928() { var test = @"/// </summary> /// <returns></returns> internal int OPERATOR() { // int?[ * @method ! new int explicit , [ 5 -- { \uDD48\uEF5C , 2, @ascending , @foreach \uD17B\u21A8 . 5 ; { /*[] bug*/ // YES [] int :: ( <= var /> { @readonly 1 <!-- 2 __makeref ? 3 @descending , 4 @float , 5 } disable ;/*,;*/ int -= _\uAEC4 - ( operator int <<= a => += ] @abstract ; property /*[]*/ i = i double + i - @async - i ' & i ) i & @using # @byte , \u7EE1\u8B45 ;/*+ - * / % & | ^*/ bool b %= = true } fixed | class join ^ ?> true ;/*& | ^*/ b ^= ! @null ;/*!*/ @stackalloc = @in == @default ;/*~i*/ b \ i base < / i - await ) && @into ( new i pragma + 1 @for ) > i _\uE02B\u7325 ; else /*< && >*/ continue @double = _Ƚ揞 in ^ 1 internal :: 0;/*? :*/ // YES : i++ ~ /*++*/ _\u560C\uF27E\uB73F -- @sizeof ;/*--*/ b @public = /= enum && params false >> true;/*&& ||*/ i @explicit # @byte >>= await ;/*<<*/ @sbyte = @operator i >> 5;/*>>*/ int @from = i; b >> @protected == ) j && assembly i @const != j "" |= i <= @explicit && @await >= @typeof ;/*= == && != <= >=*/ i @long >>= (int ]]> &= ( /*+=*/ i _Ƚ揞 -= i explicit -> /*-=*/ i { i -= /**=*/ if ] ( <<= i @assembly ) 0 . @select ++; "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(2771, "https://github.com/dotnet/roslyn/issues/2771")] [ConditionalFact(typeof(IsRelease))] public void TestBinary() { CSharpSyntaxTree.ParseText(new RandomizedSourceText()); } [WorkItem(8200, "https://github.com/dotnet/roslyn/issues/8200")] [Fact] public void EolParsing() { var code = "\n\r"; // Note, it's not "\r\n" var tree = CSharpSyntaxTree.ParseText(code); var lines1 = tree.GetText().Lines.Count; // 3 var textSpan = Text.TextSpan.FromBounds(0, tree.Length); var fileLinePositionSpan = tree.GetLineSpan(textSpan); // throws ArgumentOutOfRangeException var endLinePosition = fileLinePositionSpan.EndLinePosition; var line = endLinePosition.Line; var lines2 = line + 1; } [WorkItem(12197, "https://github.com/dotnet/roslyn/issues/12197")] [Fact] public void ThrowInInvocationCompletes() { var code = "SomeMethod(throw new Exception())"; SyntaxFactory.ParseExpression(code); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13719")] public void ReportErrorForIncompleteMember() { var test = @" class A { [Obsolete(2l)] public int }"; ParseAndValidate(test, // (6,1): error CS1519: Invalid token '}' in class, record, struct, or interface member declaration // } Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "}").WithArguments("}").WithLocation(6, 1), // (4,16): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // [Obsolete(2l)] Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 16) ); } [Fact] [WorkItem(217398, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=217398")] public void LexerTooManyBadTokens() { var source = new StringBuilder(); for (int i = 0; i <= 200; i++) { source.Append(@"\u003C"); } source.Append(@"\u003E\u003E\u003E\u003E"); var parsedTree = ParseWithRoundTripCheck(source.ToString()); IEnumerable<Diagnostic> actualErrors = parsedTree.GetDiagnostics(); Assert.Equal("202", actualErrors.Count().ToString()); Assert.Equal("(1,1201): error CS1056: Unexpected character '\\u003C'", actualErrors.ElementAt(200).ToString(EnsureEnglishUICulture.PreferredOrNull)); Assert.Equal("(1,1207): error CS1056: Unexpected character '\\u003E\\u003E\\u003E\\u003E'", actualErrors.ElementAt(201).ToString(EnsureEnglishUICulture.PreferredOrNull)); } [Fact] [WorkItem(217398, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=217398")] public void LexerTooManyBadTokens_LongUnicode() { var source = new StringBuilder(); for (int i = 0; i <= 200; i++) { source.Append(@"\U0000003C"); } source.Append(@"\u003E\u003E\u003E\u003E"); var parsedTree = ParseWithRoundTripCheck(source.ToString()); IEnumerable<Diagnostic> actualErrors = parsedTree.GetDiagnostics(); Assert.Equal("202", actualErrors.Count().ToString()); Assert.Equal("(1,2001): error CS1056: Unexpected character '\\U0000003C'", actualErrors.ElementAt(200).ToString(EnsureEnglishUICulture.PreferredOrNull)); Assert.Equal("(1,2011): error CS1056: Unexpected character '\\u003E\\u003E\\u003E\\u003E'", actualErrors.ElementAt(201).ToString(EnsureEnglishUICulture.PreferredOrNull)); } [Fact] public void QualifiedName_01() { var source = @"class Program { static void Main() { A::B.C<D> x; } }"; ParseAndValidate(source); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void QualifiedName_02() { var source = @"class Program { static void Main() { A::B.C<D> x, A::B.C<D> y; } }"; ParseAndValidate(source, // (6,10): error CS1002: ; expected // A::B.C<D> y; Diagnostic(ErrorCode.ERR_SemicolonExpected, "::").WithLocation(6, 10), // (6,10): error CS1001: Identifier expected // A::B.C<D> y; Diagnostic(ErrorCode.ERR_IdentifierExpected, "::").WithLocation(6, 10)); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "A"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void QualifiedName_03() { var source = @"class Program { static void Main() { ::A.B<C> x; } }"; ParseAndValidate(source, // (4,6): error CS1001: Identifier expected // { Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(4, 6)); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void QualifiedName_04() { var source = @"class Program { static void Main() { ::A.B<C>(); } }"; ParseAndValidate(source, // (4,6): error CS1001: Identifier expected // { Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(4, 6)); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.AliasQualifiedName); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void QualifiedName_05() { var source = @"class Program { static void Main() { A<B>::C(); } }"; ParseAndValidate(source, // (5,13): error CS1001: Identifier expected // A<B>::C(); Diagnostic(ErrorCode.ERR_IdentifierExpected, "::").WithLocation(5, 13)); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.AliasQualifiedName); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void QualifiedName_07() { var source = @"class Program { static void Main() { A<B>::C d; } }"; ParseAndValidate(source, // (5,13): error CS7000: Unexpected use of an aliased name // A<B>::C d; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithArguments("::").WithLocation(5, 13)); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.GreaterThanToken); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } #region "Helpers" private static new void ParseAndValidate(string text, params DiagnosticDescription[] expectedErrors) { var parsedTree = ParseWithRoundTripCheck(text); var actualErrors = parsedTree.GetDiagnostics(); actualErrors.Verify(expectedErrors); } #endregion "Helpers" } }
// 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 Roslyn.Test.Utilities.Syntax; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { public class ParserRegressionTests : ParsingTests { public ParserRegressionTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options ?? TestOptions.Regular); } [Fact] public void PartialLocationInModifierList() { var comp = CreateCompilation(@" class Program { partial abstract class A {} partial abstract class A {} partial partial class B {} partial partial class B {} partial abstract struct S {} partial abstract struct S {} }"); comp.VerifyDiagnostics( // (4,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial abstract class A {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(4, 5), // (5,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial abstract class A {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(5, 5), // (7,13): error CS1525: Invalid expression term 'partial' // partial partial class B {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(7, 13), // (7,13): error CS1002: ; expected // partial partial class B {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(7, 13), // (8,13): error CS1525: Invalid expression term 'partial' // partial partial class B {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(8, 13), // (8,13): error CS1002: ; expected // partial partial class B {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(8, 13), // (10,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial abstract struct S {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(10, 5), // (11,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial abstract struct S {} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(11, 5), // (10,29): error CS0106: The modifier 'abstract' is not valid for this item // partial abstract struct S {} Diagnostic(ErrorCode.ERR_BadMemberFlag, "S").WithArguments("abstract").WithLocation(10, 29), // (8,13): error CS0102: The type 'Program' already contains a definition for '' // partial partial class B {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("Program", "").WithLocation(8, 13), // (8,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // partial partial class B {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(8, 5), // (7,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // partial partial class B {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(7, 5)); } [WorkItem(540005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540005")] [Fact] public void c01() { var test = @"/// \u2750\uDFC1 = </ @goto </ ascending abstract + ( descending __arglist + descending @if <? @switch + global @long + @orderby \u23DC\u6D71\u5070\u9350 ++ into _\u6105\uE331\u27D0 # join [ + break @extern [ @char << partial | + remove + do @else + @typeof @private + "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540006")] [Fact] public void c02() { var test = @"internal int TYPES() { break retVal = @while ; __reftype CLASS c = dynamic descending CLASS( % ; on IF xx = module _4䓞 |= \u14DB\u0849 <![CDATA[ c => @default $ retVal @assembly += c void .Member & -= ; @typeof "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")] [Fact] public void c03() { var test = @"/// </summary> /// <returns></returns> else int OPERATOR @uint $ ) { - static ? operator :: ] @readonly = @on async int? , [ return ] { 1 ! , @property & 3 ! @case % partial += ;/*[] bug*/ // YES [] int % ] endregion var = ]]> @for |= @struct , 3, lock 4 @on % 5 goto } @stackalloc } /*,;*/ int %= i = @fixed ?> int << a base <= 1] default ; "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")] [Fact] public void c04() { var test = @"/// </summary> /// <returns></returns> internal do OPERATOR || ) { int?[] a = new int? \u14DB\u0849 [5] { 1, 2, 3, 4, @using } /= /*[] bug*/ // YES [] int[] var = { 1, 2, 3, 4, 5 } $ /*,;*/ int i = ; int)a[1];/*[]*/ i = i <<= @__arglist - i @sbyte * @extern / i % i ++ % i || @checked ^ i; /*+ - * / % & | ^*/ "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")] [Fact] public void c000138() { var test = @"int?[] /// a = new int? . @string ] { 1, typeof $ 3, 4, 5 } static ; @partial /*[] bug*/ // YES [] int[] var = { 1, else , 3 </ 4 | 5 };/*,;*/ int i = (int)a @in [ __refvalue ] [ /*[]*/ @readonly = i + i - abstract @typevar * i / @this % i & , i | i ^ unchecked i; in /*+ - * / % & | ^*/ bool b = true & false + | true ^ false readonly ;/*& | ^*/ @unsafe = !b;/*!*/ i = ~i;/*~i*/ b = i < (i - 1 @for ) && (i + 1) > i;/*< && >*/ "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")] [Fact] public void c000241() { var test = @"/// </summary> /// <returns></returns> const by TYPES ascending / ) $ { @let int @byte @by | 0 ; "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")] [Fact] public void c024928() { var test = @"/// </summary> /// <returns></returns> internal int OPERATOR() { // int?[ * @method ! new int explicit , [ 5 -- { \uDD48\uEF5C , 2, @ascending , @foreach \uD17B\u21A8 . 5 ; { /*[] bug*/ // YES [] int :: ( <= var /> { @readonly 1 <!-- 2 __makeref ? 3 @descending , 4 @float , 5 } disable ;/*,;*/ int -= _\uAEC4 - ( operator int <<= a => += ] @abstract ; property /*[]*/ i = i double + i - @async - i ' & i ) i & @using # @byte , \u7EE1\u8B45 ;/*+ - * / % & | ^*/ bool b %= = true } fixed | class join ^ ?> true ;/*& | ^*/ b ^= ! @null ;/*!*/ @stackalloc = @in == @default ;/*~i*/ b \ i base < / i - await ) && @into ( new i pragma + 1 @for ) > i _\uE02B\u7325 ; else /*< && >*/ continue @double = _Ƚ揞 in ^ 1 internal :: 0;/*? :*/ // YES : i++ ~ /*++*/ _\u560C\uF27E\uB73F -- @sizeof ;/*--*/ b @public = /= enum && params false >> true;/*&& ||*/ i @explicit # @byte >>= await ;/*<<*/ @sbyte = @operator i >> 5;/*>>*/ int @from = i; b >> @protected == ) j && assembly i @const != j "" |= i <= @explicit && @await >= @typeof ;/*= == && != <= >=*/ i @long >>= (int ]]> &= ( /*+=*/ i _Ƚ揞 -= i explicit -> /*-=*/ i { i -= /**=*/ if ] ( <<= i @assembly ) 0 . @select ++; "; var tree = SyntaxFactory.ParseSyntaxTree(test); } [WorkItem(2771, "https://github.com/dotnet/roslyn/issues/2771")] [ConditionalFact(typeof(IsRelease))] public void TestBinary() { CSharpSyntaxTree.ParseText(new RandomizedSourceText()); } [WorkItem(8200, "https://github.com/dotnet/roslyn/issues/8200")] [Fact] public void EolParsing() { var code = "\n\r"; // Note, it's not "\r\n" var tree = CSharpSyntaxTree.ParseText(code); var lines1 = tree.GetText().Lines.Count; // 3 var textSpan = Text.TextSpan.FromBounds(0, tree.Length); var fileLinePositionSpan = tree.GetLineSpan(textSpan); // throws ArgumentOutOfRangeException var endLinePosition = fileLinePositionSpan.EndLinePosition; var line = endLinePosition.Line; var lines2 = line + 1; } [WorkItem(12197, "https://github.com/dotnet/roslyn/issues/12197")] [Fact] public void ThrowInInvocationCompletes() { var code = "SomeMethod(throw new Exception())"; SyntaxFactory.ParseExpression(code); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13719")] public void ReportErrorForIncompleteMember() { var test = @" class A { [Obsolete(2l)] public int }"; ParseAndValidate(test, // (6,1): error CS1519: Invalid token '}' in class, record, struct, or interface member declaration // } Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "}").WithArguments("}").WithLocation(6, 1), // (4,16): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // [Obsolete(2l)] Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 16) ); } [Fact] [WorkItem(217398, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=217398")] public void LexerTooManyBadTokens() { var source = new StringBuilder(); for (int i = 0; i <= 200; i++) { source.Append(@"\u003C"); } source.Append(@"\u003E\u003E\u003E\u003E"); var parsedTree = ParseWithRoundTripCheck(source.ToString()); IEnumerable<Diagnostic> actualErrors = parsedTree.GetDiagnostics(); Assert.Equal("202", actualErrors.Count().ToString()); Assert.Equal("(1,1201): error CS1056: Unexpected character '\\u003C'", actualErrors.ElementAt(200).ToString(EnsureEnglishUICulture.PreferredOrNull)); Assert.Equal("(1,1207): error CS1056: Unexpected character '\\u003E\\u003E\\u003E\\u003E'", actualErrors.ElementAt(201).ToString(EnsureEnglishUICulture.PreferredOrNull)); } [Fact] [WorkItem(217398, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=217398")] public void LexerTooManyBadTokens_LongUnicode() { var source = new StringBuilder(); for (int i = 0; i <= 200; i++) { source.Append(@"\U0000003C"); } source.Append(@"\u003E\u003E\u003E\u003E"); var parsedTree = ParseWithRoundTripCheck(source.ToString()); IEnumerable<Diagnostic> actualErrors = parsedTree.GetDiagnostics(); Assert.Equal("202", actualErrors.Count().ToString()); Assert.Equal("(1,2001): error CS1056: Unexpected character '\\U0000003C'", actualErrors.ElementAt(200).ToString(EnsureEnglishUICulture.PreferredOrNull)); Assert.Equal("(1,2011): error CS1056: Unexpected character '\\u003E\\u003E\\u003E\\u003E'", actualErrors.ElementAt(201).ToString(EnsureEnglishUICulture.PreferredOrNull)); } [Fact] public void QualifiedName_01() { var source = @"class Program { static void Main() { A::B.C<D> x; } }"; ParseAndValidate(source); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void QualifiedName_02() { var source = @"class Program { static void Main() { A::B.C<D> x, A::B.C<D> y; } }"; ParseAndValidate(source, // (6,10): error CS1002: ; expected // A::B.C<D> y; Diagnostic(ErrorCode.ERR_SemicolonExpected, "::").WithLocation(6, 10), // (6,10): error CS1001: Identifier expected // A::B.C<D> y; Diagnostic(ErrorCode.ERR_IdentifierExpected, "::").WithLocation(6, 10)); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "A"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void QualifiedName_03() { var source = @"class Program { static void Main() { ::A.B<C> x; } }"; ParseAndValidate(source, // (4,6): error CS1001: Identifier expected // { Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(4, 6)); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void QualifiedName_04() { var source = @"class Program { static void Main() { ::A.B<C>(); } }"; ParseAndValidate(source, // (4,6): error CS1001: Identifier expected // { Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(4, 6)); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.AliasQualifiedName); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void QualifiedName_05() { var source = @"class Program { static void Main() { A<B>::C(); } }"; ParseAndValidate(source, // (5,13): error CS1001: Identifier expected // A<B>::C(); Diagnostic(ErrorCode.ERR_IdentifierExpected, "::").WithLocation(5, 13)); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.AliasQualifiedName); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void QualifiedName_07() { var source = @"class Program { static void Main() { A<B>::C d; } }"; ParseAndValidate(source, // (5,13): error CS7000: Unexpected use of an aliased name // A<B>::C d; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithArguments("::").WithLocation(5, 13)); UsingTree(source); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "Program"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Main"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.GreaterThanToken); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } #region "Helpers" private static new void ParseAndValidate(string text, params DiagnosticDescription[] expectedErrors) { var parsedTree = ParseWithRoundTripCheck(text); var actualErrors = parsedTree.GetDiagnostics(); actualErrors.Verify(expectedErrors); } #endregion "Helpers" } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Portable/BoundTree/BoundDiscardExpression.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.Symbols; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundDiscardExpression { public BoundExpression SetInferredTypeWithAnnotations(TypeWithAnnotations type) { Debug.Assert(Type is null && type.HasType); return this.Update(type.Type); } public BoundDiscardExpression FailInference(Binder binder, BindingDiagnosticBag? diagnosticsOpt) { if (diagnosticsOpt?.DiagnosticBag != null) { Binder.Error(diagnosticsOpt, ErrorCode.ERR_DiscardTypeInferenceFailed, this.Syntax); } return this.Update(binder.CreateErrorType("var")); } public override Symbol ExpressionSymbol { get { Debug.Assert(this.Type is { }); return new DiscardSymbol(TypeWithAnnotations.Create(this.Type, this.TopLevelNullability.Annotation.ToInternalAnnotation())); } } } }
// 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.Symbols; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundDiscardExpression { public BoundExpression SetInferredTypeWithAnnotations(TypeWithAnnotations type) { Debug.Assert(Type is null && type.HasType); return this.Update(type.Type); } public BoundDiscardExpression FailInference(Binder binder, BindingDiagnosticBag? diagnosticsOpt) { if (diagnosticsOpt?.DiagnosticBag != null) { Binder.Error(diagnosticsOpt, ErrorCode.ERR_DiscardTypeInferenceFailed, this.Syntax); } return this.Update(binder.CreateErrorType("var")); } public override Symbol ExpressionSymbol { get { Debug.Assert(this.Type is { }); return new DiscardSymbol(TypeWithAnnotations.Create(this.Type, this.TopLevelNullability.Annotation.ToInternalAnnotation())); } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/CodeStyle/CSharp/CodeFixes/PublicAPI.Unshipped.txt
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/PEWriter/MetadataWriter.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 System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.Cci { internal abstract partial class MetadataWriter { internal static readonly Encoding s_utf8Encoding = Encoding.UTF8; /// <summary> /// This is the maximum length of a type or member name in metadata, assuming /// the name is in UTF-8 format and not (yet) null-terminated. /// </summary> /// <remarks> /// Source names may have to be shorter still to accommodate mangling. /// Used for event names, field names, property names, field names, method def names, /// member ref names, type def (full) names, type ref (full) names, exported type /// (full) names, parameter names, manifest resource names, and unmanaged method names /// (ImplMap table). /// /// See CLI Part II, section 22. /// </remarks> internal const int NameLengthLimit = 1024 - 1; //MAX_CLASS_NAME = 1024 in dev11 /// <summary> /// This is the maximum length of a path in metadata, assuming the path is in UTF-8 /// format and not (yet) null-terminated. /// </summary> /// <remarks> /// Used for file names, module names, and module ref names. /// /// See CLI Part II, section 22. /// </remarks> internal const int PathLengthLimit = 260 - 1; //MAX_PATH = 1024 in dev11 /// <summary> /// This is the maximum length of a string in the PDB, assuming it is in UTF-8 format /// and not (yet) null-terminated. /// </summary> /// <remarks> /// Used for import strings, locals, and local constants. /// </remarks> internal const int PdbLengthLimit = 2046; // Empirical, based on when ISymUnmanagedWriter2 methods start throwing. private readonly int _numTypeDefsEstimate; private readonly bool _deterministic; internal readonly bool MetadataOnly; internal readonly bool EmitTestCoverageData; // A map of method body before token translation to RVA. Used for deduplication of small bodies. private readonly Dictionary<(ImmutableArray<byte>, bool), int> _smallMethodBodies; private const byte TinyFormat = 2; private const int ThrowNullCodeSize = 2; private static readonly ImmutableArray<byte> ThrowNullEncodedBody = ImmutableArray.Create( (byte)((ThrowNullCodeSize << 2) | TinyFormat), (byte)ILOpCode.Ldnull, (byte)ILOpCode.Throw); protected MetadataWriter( MetadataBuilder metadata, MetadataBuilder debugMetadataOpt, DynamicAnalysisDataWriter dynamicAnalysisDataWriterOpt, EmitContext context, CommonMessageProvider messageProvider, bool metadataOnly, bool deterministic, bool emitTestCoverageData, CancellationToken cancellationToken) { Debug.Assert(metadata != debugMetadataOpt); this.module = context.Module; _deterministic = deterministic; this.MetadataOnly = metadataOnly; this.EmitTestCoverageData = emitTestCoverageData; // EDMAURER provide some reasonable size estimates for these that will avoid // much of the reallocation that would occur when growing these from empty. _signatureIndex = new Dictionary<ISignature, KeyValuePair<BlobHandle, ImmutableArray<byte>>>(module.HintNumberOfMethodDefinitions, ReferenceEqualityComparer.Instance); //ignores field signatures _numTypeDefsEstimate = module.HintNumberOfMethodDefinitions / 6; this.Context = context; this.messageProvider = messageProvider; _cancellationToken = cancellationToken; this.metadata = metadata; _debugMetadataOpt = debugMetadataOpt; _dynamicAnalysisDataWriterOpt = dynamicAnalysisDataWriterOpt; _smallMethodBodies = new Dictionary<(ImmutableArray<byte>, bool), int>(ByteSequenceBoolTupleComparer.Instance); } private int NumberOfTypeDefsEstimate { get { return _numTypeDefsEstimate; } } /// <summary> /// Returns true if writing full metadata, false if writing delta. /// </summary> internal bool IsFullMetadata { get { return this.Generation == 0; } } /// <summary> /// True if writing delta metadata in a minimal format. /// </summary> private bool IsMinimalDelta { get { return !IsFullMetadata; } } /// <summary> /// NetModules and EnC deltas don't have AssemblyDef record. /// We don't emit it for EnC deltas since assembly identity has to be preserved across generations (CLR/debugger get confused otherwise). /// </summary> private bool EmitAssemblyDefinition => module.OutputKind != OutputKind.NetModule && !IsMinimalDelta; /// <summary> /// Returns metadata generation ordinal. Zero for /// full metadata and non-zero for delta. /// </summary> protected abstract ushort Generation { get; } /// <summary> /// Returns unique Guid for this delta, or default(Guid) /// if full metadata. /// </summary> protected abstract Guid EncId { get; } /// <summary> /// Returns Guid of previous delta, or default(Guid) /// if full metadata or generation 1 delta. /// </summary> protected abstract Guid EncBaseId { get; } /// <summary> /// Returns true and full metadata handle of the type definition /// if the type definition is recognized. Otherwise returns false. /// </summary> protected abstract bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle); /// <summary> /// Get full metadata handle of the type definition. /// </summary> protected abstract TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def); /// <summary> /// The type definition corresponding to full metadata type handle. /// Deltas are only required to support indexing into current generation. /// </summary> protected abstract ITypeDefinition GetTypeDef(TypeDefinitionHandle handle); /// <summary> /// The type definitions to be emitted, in row order. These /// are just the type definitions from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeDefinition> GetTypeDefs(); /// <summary> /// Get full metadata handle of the event definition. /// </summary> protected abstract EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def); /// <summary> /// The event definitions to be emitted, in row order. These /// are just the event definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IEventDefinition> GetEventDefs(); /// <summary> /// Get full metadata handle of the field definition. /// </summary> protected abstract FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def); /// <summary> /// The field definitions to be emitted, in row order. These /// are just the field definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IFieldDefinition> GetFieldDefs(); /// <summary> /// Returns true and handle of the method definition /// if the method definition is recognized. Otherwise returns false. /// The index is into the full metadata. /// </summary> protected abstract bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle); /// <summary> /// Get full metadata handle of the method definition. /// </summary> protected abstract MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def); /// <summary> /// The method definition corresponding to full metadata method handle. /// Deltas are only required to support indexing into current generation. /// </summary> protected abstract IMethodDefinition GetMethodDef(MethodDefinitionHandle handle); /// <summary> /// The method definitions to be emitted, in row order. These /// are just the method definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IMethodDefinition> GetMethodDefs(); /// <summary> /// Get full metadata handle of the property definition. /// </summary> protected abstract PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def); /// <summary> /// The property definitions to be emitted, in row order. These /// are just the property definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IPropertyDefinition> GetPropertyDefs(); /// <summary> /// The full metadata handle of the parameter definition. /// </summary> protected abstract ParameterHandle GetParameterHandle(IParameterDefinition def); /// <summary> /// The parameter definitions to be emitted, in row order. These /// are just the parameter definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IParameterDefinition> GetParameterDefs(); /// <summary> /// The generic parameter definitions to be emitted, in row order. These /// are just the generic parameter definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IGenericParameter> GetGenericParameters(); /// <summary> /// The handle of the first field of the type. /// </summary> protected abstract FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef); /// <summary> /// The handle of the first method of the type. /// </summary> protected abstract MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef); /// <summary> /// The handle of the first parameter of the method. /// </summary> protected abstract ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef); /// <summary> /// Return full metadata handle of the assembly reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference); /// <summary> /// The assembly references to be emitted, in row order. These /// are just the assembly references from the current generation. /// </summary> protected abstract IReadOnlyList<AssemblyIdentity> GetAssemblyRefs(); // ModuleRef table contains module names for TypeRefs that target types in netmodules (represented by IModuleReference), // and module names specified by P/Invokes (plain strings). Names in the table must be unique and are case sensitive. // // Spec 22.31 (ModuleRef : 0x1A) // "Name should match an entry in the Name column of the File table. Moreover, that entry shall enable the // CLI to locate the target module (typically it might name the file used to hold the module)" // // This is not how the Dev10 compilers and ILASM work. An entry is added to File table only for resources and netmodules. // Entries aren't added for P/Invoked modules. /// <summary> /// Return full metadata handle of the module reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference); /// <summary> /// The module references to be emitted, in row order. These /// are just the module references from the current generation. /// </summary> protected abstract IReadOnlyList<string> GetModuleRefs(); /// <summary> /// Return full metadata handle of the member reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference); /// <summary> /// The member references to be emitted, in row order. These /// are just the member references from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeMemberReference> GetMemberRefs(); /// <summary> /// Return full metadata handle of the method spec, adding /// the spec to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference); /// <summary> /// The method specs to be emitted, in row order. These /// are just the method specs from the current generation. /// </summary> protected abstract IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs(); /// <summary> /// The greatest index given to any method definition. /// </summary> protected abstract int GreatestMethodDefIndex { get; } /// <summary> /// Return true and full metadata handle of the type reference /// if the reference is available in the current generation. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle); /// <summary> /// Return full metadata handle of the type reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference); /// <summary> /// The type references to be emitted, in row order. These /// are just the type references from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeReference> GetTypeRefs(); /// <summary> /// Returns full metadata handle of the type spec, adding /// the spec to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference); /// <summary> /// The type specs to be emitted, in row order. These /// are just the type specs from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeReference> GetTypeSpecs(); /// <summary> /// Returns full metadata handle the standalone signature, adding /// the signature to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle handle); /// <summary> /// The signature blob handles to be emitted, in row order. These /// are just the signature indices from the current generation. /// </summary> protected abstract IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles(); protected abstract void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef); /// <summary> /// Return a visitor for traversing all references to be emitted. /// </summary> protected abstract ReferenceIndexer CreateReferenceVisitor(); /// <summary> /// Populate EventMap table. /// </summary> protected abstract void PopulateEventMapTableRows(); /// <summary> /// Populate PropertyMap table. /// </summary> protected abstract void PopulatePropertyMapTableRows(); protected abstract void ReportReferencesToAddedSymbols(); // If true, it is allowed to have methods not have bodies (for emitting metadata-only // assembly) private readonly CancellationToken _cancellationToken; protected readonly CommonPEModuleBuilder module; public readonly EmitContext Context; protected readonly CommonMessageProvider messageProvider; // progress: private bool _tableIndicesAreComplete; private bool _usingNonSourceDocumentNameEnumerator; private ImmutableArray<string>.Enumerator _nonSourceDocumentNameEnumerator; private EntityHandle[] _pseudoSymbolTokenToTokenMap; private object[] _pseudoSymbolTokenToReferenceMap; private UserStringHandle[] _pseudoStringTokenToTokenMap; private bool _userStringTokenOverflow; private List<string> _pseudoStringTokenToStringMap; private ReferenceIndexer _referenceVisitor; protected readonly MetadataBuilder metadata; // A builder for Portable or Embedded PDB metadata, or null if we are not emitting Portable/Embedded PDB. protected readonly MetadataBuilder _debugMetadataOpt; internal bool EmitPortableDebugMetadata => _debugMetadataOpt != null; private readonly DynamicAnalysisDataWriter _dynamicAnalysisDataWriterOpt; private readonly Dictionary<ICustomAttribute, BlobHandle> _customAttributeSignatureIndex = new Dictionary<ICustomAttribute, BlobHandle>(); private readonly Dictionary<ITypeReference, BlobHandle> _typeSpecSignatureIndex = new Dictionary<ITypeReference, BlobHandle>(ReferenceEqualityComparer.Instance); private readonly Dictionary<string, int> _fileRefIndex = new Dictionary<string, int>(32); // more than enough in most cases, value is a RowId private readonly List<IFileReference> _fileRefList = new List<IFileReference>(32); private readonly Dictionary<IFieldReference, BlobHandle> _fieldSignatureIndex = new Dictionary<IFieldReference, BlobHandle>(ReferenceEqualityComparer.Instance); // We need to keep track of both the index of the signature and the actual blob to support VB static local naming scheme. private readonly Dictionary<ISignature, KeyValuePair<BlobHandle, ImmutableArray<byte>>> _signatureIndex; private readonly Dictionary<IMarshallingInformation, BlobHandle> _marshallingDescriptorIndex = new Dictionary<IMarshallingInformation, BlobHandle>(); protected readonly List<MethodImplementation> methodImplList = new List<MethodImplementation>(); private readonly Dictionary<IGenericMethodInstanceReference, BlobHandle> _methodInstanceSignatureIndex = new Dictionary<IGenericMethodInstanceReference, BlobHandle>(ReferenceEqualityComparer.Instance); // Well known dummy cor library types whose refs are used for attaching assembly attributes off within net modules // There is no guarantee the types actually exist in a cor library internal const string dummyAssemblyAttributeParentNamespace = "System.Runtime.CompilerServices"; internal const string dummyAssemblyAttributeParentName = "AssemblyAttributesGoHere"; internal static readonly string[,] dummyAssemblyAttributeParentQualifier = { { "", "M" }, { "S", "SM" } }; private readonly TypeReferenceHandle[,] _dummyAssemblyAttributeParent = { { default(TypeReferenceHandle), default(TypeReferenceHandle) }, { default(TypeReferenceHandle), default(TypeReferenceHandle) } }; internal CommonPEModuleBuilder Module => module; private void CreateMethodBodyReferenceIndex() { var referencesInIL = module.ReferencesInIL(); _pseudoSymbolTokenToTokenMap = new EntityHandle[referencesInIL.Length]; _pseudoSymbolTokenToReferenceMap = referencesInIL.ToArray(); } private void CreateIndices() { _cancellationToken.ThrowIfCancellationRequested(); this.CreateUserStringIndices(); this.CreateInitialAssemblyRefIndex(); this.CreateInitialFileRefIndex(); this.CreateIndicesForModule(); // Find all references and assign tokens. _referenceVisitor = this.CreateReferenceVisitor(); _referenceVisitor.Visit(module); this.CreateMethodBodyReferenceIndex(); this.OnIndicesCreated(); } private void CreateUserStringIndices() { _pseudoStringTokenToStringMap = new List<string>(); foreach (string str in this.module.GetStrings()) { _pseudoStringTokenToStringMap.Add(str); } _pseudoStringTokenToTokenMap = new UserStringHandle[_pseudoStringTokenToStringMap.Count]; } private void CreateIndicesForModule() { var nestedTypes = new Queue<INestedTypeDefinition>(); foreach (INamespaceTypeDefinition typeDef in module.GetTopLevelTypeDefinitions(Context)) { this.CreateIndicesFor(typeDef, nestedTypes); } while (nestedTypes.Count > 0) { var nestedType = nestedTypes.Dequeue(); this.CreateIndicesFor(nestedType, nestedTypes); } } protected virtual void OnIndicesCreated() { } private void CreateIndicesFor(ITypeDefinition typeDef, Queue<INestedTypeDefinition> nestedTypes) { _cancellationToken.ThrowIfCancellationRequested(); this.CreateIndicesForNonTypeMembers(typeDef); // Metadata spec: // The TypeDef table has a special ordering constraint: // the definition of an enclosing class shall precede the definition of all classes it encloses. foreach (var nestedType in typeDef.GetNestedTypes(Context)) { nestedTypes.Enqueue(nestedType); } } protected IEnumerable<IGenericTypeParameter> GetConsolidatedTypeParameters(ITypeDefinition typeDef) { INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef == null) { if (typeDef.IsGeneric) { return typeDef.GenericParameters; } return null; } return this.GetConsolidatedTypeParameters(typeDef, typeDef); } private List<IGenericTypeParameter> GetConsolidatedTypeParameters(ITypeDefinition typeDef, ITypeDefinition owner) { List<IGenericTypeParameter> result = null; INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef != null) { result = this.GetConsolidatedTypeParameters(nestedTypeDef.ContainingTypeDefinition, owner); } if (typeDef.GenericParameterCount > 0) { ushort index = 0; if (result == null) { result = new List<IGenericTypeParameter>(); } else { index = (ushort)result.Count; } if (typeDef == owner && index == 0) { result.AddRange(typeDef.GenericParameters); } else { foreach (IGenericTypeParameter genericParameter in typeDef.GenericParameters) { result.Add(new InheritedTypeParameter(index++, owner, genericParameter)); } } } return result; } protected ImmutableArray<IParameterDefinition> GetParametersToEmit(IMethodDefinition methodDef) { if (methodDef.ParameterCount == 0 && !(methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context)))) { return ImmutableArray<IParameterDefinition>.Empty; } return GetParametersToEmitCore(methodDef); } private ImmutableArray<IParameterDefinition> GetParametersToEmitCore(IMethodDefinition methodDef) { ArrayBuilder<IParameterDefinition> builder = null; var parameters = methodDef.Parameters; if (methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context))) { builder = ArrayBuilder<IParameterDefinition>.GetInstance(parameters.Length + 1); builder.Add(new ReturnValueParameter(methodDef)); } for (int i = 0; i < parameters.Length; i++) { IParameterDefinition parDef = parameters[i]; // No explicit param row is needed if param has no flags (other than optionally IN), // no name and no references to the param row, such as CustomAttribute, Constant, or FieldMarshal if (parDef.Name != String.Empty || parDef.HasDefaultValue || parDef.IsOptional || parDef.IsOut || parDef.IsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(parDef.GetAttributes(Context))) { if (builder != null) { builder.Add(parDef); } } else { // we have a parameter that does not need to be emitted (not common) if (builder == null) { builder = ArrayBuilder<IParameterDefinition>.GetInstance(parameters.Length); builder.AddRange(parameters, i); } } } return builder?.ToImmutableAndFree() ?? parameters; } /// <summary> /// Returns a reference to the unit that defines the given referenced type. If the referenced type is a structural type, such as a pointer or a generic type instance, /// then the result is null. /// </summary> public static IUnitReference GetDefiningUnitReference(ITypeReference typeReference, EmitContext context) { INestedTypeReference nestedTypeReference = typeReference.AsNestedTypeReference; while (nestedTypeReference != null) { if (nestedTypeReference.AsGenericTypeInstanceReference != null) { return null; } typeReference = nestedTypeReference.GetContainingType(context); nestedTypeReference = typeReference.AsNestedTypeReference; } INamespaceTypeReference namespaceTypeReference = typeReference.AsNamespaceTypeReference; if (namespaceTypeReference == null) { return null; } Debug.Assert(namespaceTypeReference.AsGenericTypeInstanceReference == null); return namespaceTypeReference.GetUnit(context); } private void CreateInitialAssemblyRefIndex() { Debug.Assert(!_tableIndicesAreComplete); foreach (IAssemblyReference assemblyRef in this.module.GetAssemblyReferences(Context)) { this.GetOrAddAssemblyReferenceHandle(assemblyRef); } } private void CreateInitialFileRefIndex() { Debug.Assert(!_tableIndicesAreComplete); foreach (IFileReference fileRef in module.GetFiles(Context)) { string key = fileRef.FileName; if (!_fileRefIndex.ContainsKey(key)) { _fileRefList.Add(fileRef); _fileRefIndex.Add(key, _fileRefList.Count); } } } internal AssemblyReferenceHandle GetAssemblyReferenceHandle(IAssemblyReference assemblyReference) { var containingAssembly = this.module.GetContainingAssembly(Context); if (containingAssembly != null && ReferenceEquals(assemblyReference, containingAssembly)) { return default(AssemblyReferenceHandle); } return this.GetOrAddAssemblyReferenceHandle(assemblyReference); } internal ModuleReferenceHandle GetModuleReferenceHandle(string moduleName) { return this.GetOrAddModuleReferenceHandle(moduleName); } private BlobHandle GetCustomAttributeSignatureIndex(ICustomAttribute customAttribute) { BlobHandle result; if (_customAttributeSignatureIndex.TryGetValue(customAttribute, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeCustomAttributeSignature(customAttribute, writer); result = metadata.GetOrAddBlob(writer); _customAttributeSignatureIndex.Add(customAttribute, result); writer.Free(); return result; } private EntityHandle GetCustomAttributeTypeCodedIndex(IMethodReference methodReference) { IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } return methodDef != null ? (EntityHandle)GetMethodDefinitionHandle(methodDef) : GetMemberReferenceHandle(methodReference); } public static EventAttributes GetEventAttributes(IEventDefinition eventDef) { EventAttributes result = 0; if (eventDef.IsSpecialName) { result |= EventAttributes.SpecialName; } if (eventDef.IsRuntimeSpecial) { result |= EventAttributes.RTSpecialName; } return result; } public static FieldAttributes GetFieldAttributes(IFieldDefinition fieldDef) { var result = (FieldAttributes)fieldDef.Visibility; if (fieldDef.IsStatic) { result |= FieldAttributes.Static; } if (fieldDef.IsReadOnly) { result |= FieldAttributes.InitOnly; } if (fieldDef.IsCompileTimeConstant) { result |= FieldAttributes.Literal; } if (fieldDef.IsNotSerialized) { result |= FieldAttributes.NotSerialized; } if (!fieldDef.MappedData.IsDefault) { result |= FieldAttributes.HasFieldRVA; } if (fieldDef.IsSpecialName) { result |= FieldAttributes.SpecialName; } if (fieldDef.IsRuntimeSpecial) { result |= FieldAttributes.RTSpecialName; } if (fieldDef.IsMarshalledExplicitly) { result |= FieldAttributes.HasFieldMarshal; } if (fieldDef.IsCompileTimeConstant) { result |= FieldAttributes.HasDefault; } return result; } internal BlobHandle GetFieldSignatureIndex(IFieldReference fieldReference) { BlobHandle result; ISpecializedFieldReference specializedFieldReference = fieldReference.AsSpecializedFieldReference; if (specializedFieldReference != null) { fieldReference = specializedFieldReference.UnspecializedVersion; } if (_fieldSignatureIndex.TryGetValue(fieldReference, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeFieldSignature(fieldReference, writer); result = metadata.GetOrAddBlob(writer); _fieldSignatureIndex.Add(fieldReference, result); writer.Free(); return result; } internal EntityHandle GetFieldHandle(IFieldReference fieldReference) { IFieldDefinition fieldDef = null; IUnitReference definingUnit = GetDefiningUnitReference(fieldReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { fieldDef = fieldReference.GetResolvedField(Context); } return fieldDef != null ? (EntityHandle)GetFieldDefinitionHandle(fieldDef) : GetMemberReferenceHandle(fieldReference); } internal AssemblyFileHandle GetAssemblyFileHandle(IFileReference fileReference) { string key = fileReference.FileName; int index; if (!_fileRefIndex.TryGetValue(key, out index)) { Debug.Assert(!_tableIndicesAreComplete); _fileRefList.Add(fileReference); _fileRefIndex.Add(key, index = _fileRefList.Count); } return MetadataTokens.AssemblyFileHandle(index); } private AssemblyFileHandle GetAssemblyFileHandle(IModuleReference mref) { return MetadataTokens.AssemblyFileHandle(_fileRefIndex[mref.Name]); } private static GenericParameterAttributes GetGenericParameterAttributes(IGenericParameter genPar) { GenericParameterAttributes result = 0; switch (genPar.Variance) { case TypeParameterVariance.Covariant: result |= GenericParameterAttributes.Covariant; break; case TypeParameterVariance.Contravariant: result |= GenericParameterAttributes.Contravariant; break; } if (genPar.MustBeReferenceType) { result |= GenericParameterAttributes.ReferenceTypeConstraint; } if (genPar.MustBeValueType) { result |= GenericParameterAttributes.NotNullableValueTypeConstraint; } if (genPar.MustHaveDefaultConstructor) { result |= GenericParameterAttributes.DefaultConstructorConstraint; } return result; } private EntityHandle GetExportedTypeImplementation(INamespaceTypeReference namespaceRef) { IUnitReference uref = namespaceRef.GetUnit(Context); if (uref is IAssemblyReference aref) { return GetAssemblyReferenceHandle(aref); } var mref = (IModuleReference)uref; aref = mref.GetContainingAssembly(Context); return aref == null || ReferenceEquals(aref, this.module.GetContainingAssembly(Context)) ? (EntityHandle)GetAssemblyFileHandle(mref) : GetAssemblyReferenceHandle(aref); } private static uint GetManagedResourceOffset(ManagedResource resource, BlobBuilder resourceWriter) { if (resource.ExternalFile != null) { return resource.Offset; } int result = resourceWriter.Count; resource.WriteData(resourceWriter); return (uint)result; } private static uint GetManagedResourceOffset(BlobBuilder resource, BlobBuilder resourceWriter) { int result = resourceWriter.Count; resourceWriter.WriteInt32(resource.Count); resource.WriteContentTo(resourceWriter); resourceWriter.Align(8); return (uint)result; } public static string GetMangledName(INamedTypeReference namedType, int generation) { string unmangledName = (generation == 0) ? namedType.Name : namedType.Name + "#" + generation; return namedType.MangleName ? MetadataHelpers.ComposeAritySuffixedMetadataName(unmangledName, namedType.GenericParameterCount) : unmangledName; } internal MemberReferenceHandle GetMemberReferenceHandle(ITypeMemberReference memberRef) { return this.GetOrAddMemberReferenceHandle(memberRef); } internal EntityHandle GetMemberReferenceParent(ITypeMemberReference memberRef) { ITypeDefinition parentTypeDef = memberRef.GetContainingType(Context).AsTypeDefinition(Context); if (parentTypeDef != null) { TypeDefinitionHandle parentTypeDefHandle; TryGetTypeDefinitionHandle(parentTypeDef, out parentTypeDefHandle); if (!parentTypeDefHandle.IsNil) { if (memberRef is IFieldReference) { return parentTypeDefHandle; } if (memberRef is IMethodReference methodRef) { if (methodRef.AcceptsExtraArguments) { MethodDefinitionHandle methodHandle; if (this.TryGetMethodDefinitionHandle(methodRef.GetResolvedMethod(Context), out methodHandle)) { return methodHandle; } } return parentTypeDefHandle; } // TODO: error } } // TODO: special treatment for global fields and methods. Object model support would be nice. var containingType = memberRef.GetContainingType(Context); return containingType.IsTypeSpecification() ? (EntityHandle)GetTypeSpecificationHandle(containingType) : GetTypeReferenceHandle(containingType); } internal EntityHandle GetMethodDefinitionOrReferenceHandle(IMethodReference methodReference) { IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } return methodDef != null ? (EntityHandle)GetMethodDefinitionHandle(methodDef) : GetMemberReferenceHandle(methodReference); } public static MethodAttributes GetMethodAttributes(IMethodDefinition methodDef) { var result = (MethodAttributes)methodDef.Visibility; if (methodDef.IsStatic) { result |= MethodAttributes.Static; } if (methodDef.IsSealed) { result |= MethodAttributes.Final; } if (methodDef.IsVirtual) { result |= MethodAttributes.Virtual; } if (methodDef.IsHiddenBySignature) { result |= MethodAttributes.HideBySig; } if (methodDef.IsNewSlot) { result |= MethodAttributes.NewSlot; } if (methodDef.IsAccessCheckedOnOverride) { result |= MethodAttributes.CheckAccessOnOverride; } if (methodDef.IsAbstract) { result |= MethodAttributes.Abstract; } if (methodDef.IsSpecialName) { result |= MethodAttributes.SpecialName; } if (methodDef.IsRuntimeSpecial) { result |= MethodAttributes.RTSpecialName; } if (methodDef.IsPlatformInvoke) { result |= MethodAttributes.PinvokeImpl; } if (methodDef.HasDeclarativeSecurity) { result |= MethodAttributes.HasSecurity; } if (methodDef.RequiresSecurityObject) { result |= MethodAttributes.RequireSecObject; } return result; } internal BlobHandle GetMethodSpecificationSignatureHandle(IGenericMethodInstanceReference methodInstanceReference) { BlobHandle result; if (_methodInstanceSignatureIndex.TryGetValue(methodInstanceReference, out result)) { return result; } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).MethodSpecificationSignature(methodInstanceReference.GetGenericMethod(Context).GenericParameterCount); foreach (ITypeReference typeReference in methodInstanceReference.GetGenericArguments(Context)) { var typeRef = typeReference; SerializeTypeReference(encoder.AddArgument(), typeRef); } result = metadata.GetOrAddBlob(builder); _methodInstanceSignatureIndex.Add(methodInstanceReference, result); builder.Free(); return result; } private BlobHandle GetMarshallingDescriptorHandle(IMarshallingInformation marshallingInformation) { BlobHandle result; if (_marshallingDescriptorIndex.TryGetValue(marshallingInformation, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeMarshallingDescriptor(marshallingInformation, writer); result = metadata.GetOrAddBlob(writer); _marshallingDescriptorIndex.Add(marshallingInformation, result); writer.Free(); return result; } private BlobHandle GetMarshallingDescriptorHandle(ImmutableArray<byte> descriptor) { return metadata.GetOrAddBlob(descriptor); } private BlobHandle GetMemberReferenceSignatureHandle(ITypeMemberReference memberRef) { return memberRef switch { IFieldReference fieldReference => this.GetFieldSignatureIndex(fieldReference), IMethodReference methodReference => this.GetMethodSignatureHandle(methodReference), _ => throw ExceptionUtilities.Unreachable }; } internal BlobHandle GetMethodSignatureHandle(IMethodReference methodReference) { return GetMethodSignatureHandleAndBlob(methodReference, out _); } internal byte[] GetMethodSignature(IMethodReference methodReference) { ImmutableArray<byte> signatureBlob; GetMethodSignatureHandleAndBlob(methodReference, out signatureBlob); return signatureBlob.ToArray(); } private BlobHandle GetMethodSignatureHandleAndBlob(IMethodReference methodReference, out ImmutableArray<byte> signatureBlob) { BlobHandle result; ISpecializedMethodReference specializedMethodReference = methodReference.AsSpecializedMethodReference; if (specializedMethodReference != null) { methodReference = specializedMethodReference.UnspecializedVersion; } KeyValuePair<BlobHandle, ImmutableArray<byte>> existing; if (_signatureIndex.TryGetValue(methodReference, out existing)) { signatureBlob = existing.Value; return existing.Key; } Debug.Assert((methodReference.CallingConvention & CallingConvention.Generic) != 0 == (methodReference.GenericParameterCount > 0)); var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).MethodSignature( new SignatureHeader((byte)methodReference.CallingConvention).CallingConvention, methodReference.GenericParameterCount, isInstanceMethod: (methodReference.CallingConvention & CallingConvention.HasThis) != 0); SerializeReturnValueAndParameters(encoder, methodReference, methodReference.ExtraParameters); signatureBlob = builder.ToImmutableArray(); result = metadata.GetOrAddBlob(signatureBlob); _signatureIndex.Add(methodReference, KeyValuePairUtil.Create(result, signatureBlob)); builder.Free(); return result; } private BlobHandle GetMethodSpecificationBlobHandle(IGenericMethodInstanceReference genericMethodInstanceReference) { var writer = PooledBlobBuilder.GetInstance(); SerializeMethodSpecificationSignature(writer, genericMethodInstanceReference); BlobHandle result = metadata.GetOrAddBlob(writer); writer.Free(); return result; } private MethodSpecificationHandle GetMethodSpecificationHandle(IGenericMethodInstanceReference methodSpec) { return this.GetOrAddMethodSpecificationHandle(methodSpec); } internal EntityHandle GetMethodHandle(IMethodReference methodReference) { MethodDefinitionHandle methodDefHandle; IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } if (methodDef != null && (methodReference == methodDef || !methodReference.AcceptsExtraArguments) && this.TryGetMethodDefinitionHandle(methodDef, out methodDefHandle)) { return methodDefHandle; } IGenericMethodInstanceReference methodSpec = methodReference.AsGenericMethodInstanceReference; return methodSpec != null ? (EntityHandle)GetMethodSpecificationHandle(methodSpec) : GetMemberReferenceHandle(methodReference); } internal EntityHandle GetStandaloneSignatureHandle(ISignature signature) { Debug.Assert(!(signature is IMethodReference)); var builder = PooledBlobBuilder.GetInstance(); var signatureEncoder = new BlobEncoder(builder).MethodSignature(convention: signature.CallingConvention.ToSignatureConvention(), genericParameterCount: 0, isInstanceMethod: false); SerializeReturnValueAndParameters(signatureEncoder, signature, varargParameters: ImmutableArray<IParameterTypeInformation>.Empty); BlobHandle blobIndex = metadata.GetOrAddBlob(builder); StandaloneSignatureHandle handle = GetOrAddStandaloneSignatureHandle(blobIndex); return handle; } public static ParameterAttributes GetParameterAttributes(IParameterDefinition parDef) { ParameterAttributes result = 0; if (parDef.IsIn) { result |= ParameterAttributes.In; } if (parDef.IsOut) { result |= ParameterAttributes.Out; } if (parDef.IsOptional) { result |= ParameterAttributes.Optional; } if (parDef.HasDefaultValue) { result |= ParameterAttributes.HasDefault; } if (parDef.IsMarshalledExplicitly) { result |= ParameterAttributes.HasFieldMarshal; } return result; } private BlobHandle GetPermissionSetBlobHandle(ImmutableArray<ICustomAttribute> permissionSet) { var writer = PooledBlobBuilder.GetInstance(); BlobHandle result; try { writer.WriteByte((byte)'.'); writer.WriteCompressedInteger(permissionSet.Length); this.SerializePermissionSet(permissionSet, writer); result = metadata.GetOrAddBlob(writer); } finally { writer.Free(); } return result; } public static PropertyAttributes GetPropertyAttributes(IPropertyDefinition propertyDef) { PropertyAttributes result = 0; if (propertyDef.IsSpecialName) { result |= PropertyAttributes.SpecialName; } if (propertyDef.IsRuntimeSpecial) { result |= PropertyAttributes.RTSpecialName; } if (propertyDef.HasDefaultValue) { result |= PropertyAttributes.HasDefault; } return result; } private BlobHandle GetPropertySignatureHandle(IPropertyDefinition propertyDef) { KeyValuePair<BlobHandle, ImmutableArray<byte>> existing; if (_signatureIndex.TryGetValue(propertyDef, out existing)) { return existing.Key; } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).PropertySignature( isInstanceProperty: (propertyDef.CallingConvention & CallingConvention.HasThis) != 0); SerializeReturnValueAndParameters(encoder, propertyDef, ImmutableArray<IParameterTypeInformation>.Empty); var blob = builder.ToImmutableArray(); var result = metadata.GetOrAddBlob(blob); _signatureIndex.Add(propertyDef, KeyValuePairUtil.Create(result, blob)); builder.Free(); return result; } private EntityHandle GetResolutionScopeHandle(IUnitReference unitReference) { if (unitReference is IAssemblyReference aref) { return GetAssemblyReferenceHandle(aref); } // If this is a module from a referenced multi-module assembly, // the assembly should be used as the resolution scope. var mref = (IModuleReference)unitReference; aref = mref.GetContainingAssembly(Context); if (aref != null && aref != module.GetContainingAssembly(Context)) { return GetAssemblyReferenceHandle(aref); } return GetModuleReferenceHandle(mref.Name); } private StringHandle GetStringHandleForPathAndCheckLength(string path, INamedEntity errorEntity = null) { CheckPathLength(path, errorEntity); return metadata.GetOrAddString(path); } private StringHandle GetStringHandleForNameAndCheckLength(string name, INamedEntity errorEntity = null) { CheckNameLength(name, errorEntity); return metadata.GetOrAddString(name); } /// <summary> /// The Microsoft CLR requires that {namespace} + "." + {name} fit in MAX_CLASS_NAME /// (even though the name and namespace are stored separately in the Microsoft /// implementation). Note that the namespace name of a nested type is always blank /// (since comes from the container). /// </summary> /// <param name="namespaceType">We're trying to add the containing namespace of this type to the string heap.</param> /// <param name="mangledTypeName">Namespace names are never used on their own - this is the type that is adding the namespace name. /// Used only for length checking.</param> private StringHandle GetStringHandleForNamespaceAndCheckLength(INamespaceTypeReference namespaceType, string mangledTypeName) { string namespaceName = namespaceType.NamespaceName; if (namespaceName.Length == 0) // Optimization: CheckNamespaceLength is relatively expensive. { return default(StringHandle); } CheckNamespaceLength(namespaceName, mangledTypeName, namespaceType); return metadata.GetOrAddString(namespaceName); } private void CheckNameLength(string name, INamedEntity errorEntity) { // NOTE: ildasm shows quotes around some names (e.g. explicit implementations of members of generic interfaces) // but that seems to be tool-specific - they don't seem to and up in the string heap (so they don't count against // the length limit). if (IsTooLongInternal(name, NameLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, name)); } } private void CheckPathLength(string path, INamedEntity errorEntity = null) { if (IsTooLongInternal(path, PathLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, path)); } } private void CheckNamespaceLength(string namespaceName, string mangledTypeName, INamespaceTypeReference errorEntity) { // It's never useful to report that the namespace name is too long. // If it's too long, then the full name is too long and that string is // more helpful. // PERF: We expect to check this A LOT, so we'll aggressively inline some // of the helpers (esp IsTooLongInternal) in a way that allows us to forego // string concatenation (unless a diagnostic is actually reported). if (namespaceName.Length + 1 + mangledTypeName.Length > NameLengthLimit / 3) { int utf8Length = s_utf8Encoding.GetByteCount(namespaceName) + 1 + // dot s_utf8Encoding.GetByteCount(mangledTypeName); if (utf8Length > NameLengthLimit) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, namespaceName + "." + mangledTypeName)); } } } internal bool IsUsingStringTooLong(string usingString, INamedEntity errorEntity = null) { if (IsTooLongInternal(usingString, PdbLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.WRN_PdbUsingNameTooLong, location, usingString)); return true; } return false; } internal bool IsLocalNameTooLong(ILocalDefinition localDefinition) { string name = localDefinition.Name; if (IsTooLongInternal(name, PdbLengthLimit)) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.WRN_PdbLocalNameTooLong, localDefinition.Location, name)); return true; } return false; } /// <summary> /// Test the given name to see if it fits in metadata. /// </summary> /// <param name="str">String to test (non-null).</param> /// <param name="maxLength">Max length for name. (Expected to be at least 5.)</param> /// <returns>True if the name is too long.</returns> /// <remarks>Internal for test purposes.</remarks> internal static bool IsTooLongInternal(string str, int maxLength) { Debug.Assert(str != null); // No need to handle in an internal utility. if (str.Length < maxLength / 3) //UTF-8 uses at most 3 bytes per char { return false; } int utf8Length = s_utf8Encoding.GetByteCount(str); return utf8Length > maxLength; } private static Location GetNamedEntityLocation(INamedEntity errorEntity) { ISymbolInternal symbol; if (errorEntity is Cci.INamespace ns) { symbol = ns.GetInternalSymbol(); } else { symbol = (errorEntity as Cci.IReference)?.GetInternalSymbol(); } return GetSymbolLocation(symbol); } protected static Location GetSymbolLocation(ISymbolInternal symbolOpt) { return symbolOpt != null && !symbolOpt.Locations.IsDefaultOrEmpty ? symbolOpt.Locations[0] : Location.None; } internal TypeAttributes GetTypeAttributes(ITypeDefinition typeDef) { return GetTypeAttributes(typeDef, Context); } public static TypeAttributes GetTypeAttributes(ITypeDefinition typeDef, EmitContext context) { TypeAttributes result = 0; switch (typeDef.Layout) { case LayoutKind.Sequential: result |= TypeAttributes.SequentialLayout; break; case LayoutKind.Explicit: result |= TypeAttributes.ExplicitLayout; break; } if (typeDef.IsInterface) { result |= TypeAttributes.Interface; } if (typeDef.IsAbstract) { result |= TypeAttributes.Abstract; } if (typeDef.IsSealed) { result |= TypeAttributes.Sealed; } if (typeDef.IsSpecialName) { result |= TypeAttributes.SpecialName; } if (typeDef.IsRuntimeSpecial) { result |= TypeAttributes.RTSpecialName; } if (typeDef.IsComObject) { result |= TypeAttributes.Import; } if (typeDef.IsSerializable) { result |= TypeAttributes.Serializable; } if (typeDef.IsWindowsRuntimeImport) { result |= TypeAttributes.WindowsRuntime; } switch (typeDef.StringFormat) { case CharSet.Unicode: result |= TypeAttributes.UnicodeClass; break; case Constants.CharSet_Auto: result |= TypeAttributes.AutoClass; break; } if (typeDef.HasDeclarativeSecurity) { result |= TypeAttributes.HasSecurity; } if (typeDef.IsBeforeFieldInit) { result |= TypeAttributes.BeforeFieldInit; } INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(context); if (nestedTypeDef != null) { switch (((ITypeDefinitionMember)typeDef).Visibility) { case TypeMemberVisibility.Public: result |= TypeAttributes.NestedPublic; break; case TypeMemberVisibility.Private: result |= TypeAttributes.NestedPrivate; break; case TypeMemberVisibility.Family: result |= TypeAttributes.NestedFamily; break; case TypeMemberVisibility.Assembly: result |= TypeAttributes.NestedAssembly; break; case TypeMemberVisibility.FamilyAndAssembly: result |= TypeAttributes.NestedFamANDAssem; break; case TypeMemberVisibility.FamilyOrAssembly: result |= TypeAttributes.NestedFamORAssem; break; } return result; } INamespaceTypeDefinition namespaceTypeDef = typeDef.AsNamespaceTypeDefinition(context); if (namespaceTypeDef != null && namespaceTypeDef.IsPublic) { result |= TypeAttributes.Public; } return result; } private EntityHandle GetDeclaringTypeOrMethodHandle(IGenericParameter genPar) { IGenericTypeParameter genTypePar = genPar.AsGenericTypeParameter; if (genTypePar != null) { return GetTypeDefinitionHandle(genTypePar.DefiningType); } IGenericMethodParameter genMethPar = genPar.AsGenericMethodParameter; if (genMethPar != null) { return GetMethodDefinitionHandle(genMethPar.DefiningMethod); } throw ExceptionUtilities.Unreachable; } private TypeReferenceHandle GetTypeReferenceHandle(ITypeReference typeReference) { TypeReferenceHandle result; if (this.TryGetTypeReferenceHandle(typeReference, out result)) { return result; } // NOTE: Even though CLR documentation does not explicitly specify any requirements // NOTE: to the order of records in TypeRef table, some tools and/or APIs (e.g. // NOTE: IMetaDataEmit::MergeEnd) assume that the containing type referenced as // NOTE: ResolutionScope for its nested types should appear in TypeRef table // NOTE: *before* any of its nested types. // SEE ALSO: bug#570975 and test Bug570975() INestedTypeReference nestedTypeRef = typeReference.AsNestedTypeReference; if (nestedTypeRef != null) { GetTypeReferenceHandle(nestedTypeRef.GetContainingType(this.Context)); } return this.GetOrAddTypeReferenceHandle(typeReference); } private TypeSpecificationHandle GetTypeSpecificationHandle(ITypeReference typeReference) { return this.GetOrAddTypeSpecificationHandle(typeReference); } internal ITypeDefinition GetTypeDefinition(int token) { // The token must refer to a TypeDef row since we are // only handling indexes into the full metadata (in EnC) // for def tables. Other tables contain deltas only. return GetTypeDef(MetadataTokens.TypeDefinitionHandle(token)); } internal IMethodDefinition GetMethodDefinition(int token) { // Must be a def table. (See comment in GetTypeDefinition.) return GetMethodDef(MetadataTokens.MethodDefinitionHandle(token)); } internal INestedTypeReference GetNestedTypeReference(int token) { // Must be a def table. (See comment in GetTypeDefinition.) return GetTypeDef(MetadataTokens.TypeDefinitionHandle(token)).AsNestedTypeReference; } internal BlobHandle GetTypeSpecSignatureIndex(ITypeReference typeReference) { BlobHandle result; if (_typeSpecSignatureIndex.TryGetValue(typeReference, out result)) { return result; } var builder = PooledBlobBuilder.GetInstance(); this.SerializeTypeReference(new BlobEncoder(builder).TypeSpecificationSignature(), typeReference); result = metadata.GetOrAddBlob(builder); _typeSpecSignatureIndex.Add(typeReference, result); builder.Free(); return result; } internal EntityHandle GetTypeHandle(ITypeReference typeReference, bool treatRefAsPotentialTypeSpec = true) { TypeDefinitionHandle handle; var typeDefinition = typeReference.AsTypeDefinition(this.Context); if (typeDefinition != null && this.TryGetTypeDefinitionHandle(typeDefinition, out handle)) { return handle; } return treatRefAsPotentialTypeSpec && typeReference.IsTypeSpecification() ? (EntityHandle)GetTypeSpecificationHandle(typeReference) : GetTypeReferenceHandle(typeReference); } internal EntityHandle GetDefinitionHandle(IDefinition definition) { return definition switch { ITypeDefinition typeDef => (EntityHandle)GetTypeDefinitionHandle(typeDef), IMethodDefinition methodDef => GetMethodDefinitionHandle(methodDef), IFieldDefinition fieldDef => GetFieldDefinitionHandle(fieldDef), IEventDefinition eventDef => GetEventDefinitionHandle(eventDef), IPropertyDefinition propertyDef => GetPropertyDefIndex(propertyDef), _ => throw ExceptionUtilities.Unreachable }; } public void WriteMetadataAndIL(PdbWriter nativePdbWriterOpt, Stream metadataStream, Stream ilStream, Stream portablePdbStreamOpt, out MetadataSizes metadataSizes) { Debug.Assert(nativePdbWriterOpt == null ^ portablePdbStreamOpt == null); nativePdbWriterOpt?.SetMetadataEmitter(this); // TODO: we can precalculate the exact size of IL stream var ilBuilder = new BlobBuilder(1024); var metadataBuilder = new BlobBuilder(4 * 1024); var mappedFieldDataBuilder = new BlobBuilder(0); var managedResourceDataBuilder = new BlobBuilder(0); // Add 4B of padding to the start of the separated IL stream, // so that method RVAs, which are offsets to this stream, are never 0. ilBuilder.WriteUInt32(0); // this is used to handle edit-and-continue emit, so we should have a module // version ID that is imposed by the caller (the same as the previous module version ID). // Therefore we do not have to fill in a new module version ID in the generated metadata // stream. Debug.Assert(module.SerializationProperties.PersistentIdentifier != default(Guid)); BuildMetadataAndIL( nativePdbWriterOpt, ilBuilder, mappedFieldDataBuilder, managedResourceDataBuilder, out Blob mvidFixup, out Blob mvidStringFixup); var typeSystemRowCounts = metadata.GetRowCounts(); Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncLog] == 0); Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncMap] == 0); PopulateEncTables(typeSystemRowCounts); Debug.Assert(mappedFieldDataBuilder.Count == 0); Debug.Assert(managedResourceDataBuilder.Count == 0); Debug.Assert(mvidFixup.IsDefault); Debug.Assert(mvidStringFixup.IsDefault); // TODO (https://github.com/dotnet/roslyn/issues/3905): // InterfaceImpl table emitted by Roslyn is not compliant with ECMA spec. // Once fixed enable validation in DEBUG builds. var rootBuilder = new MetadataRootBuilder(metadata, module.SerializationProperties.TargetRuntimeVersion, suppressValidation: true); rootBuilder.Serialize(metadataBuilder, methodBodyStreamRva: 0, mappedFieldDataStreamRva: 0); metadataSizes = rootBuilder.Sizes; try { ilBuilder.WriteContentTo(ilStream); metadataBuilder.WriteContentTo(metadataStream); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new PeWritingException(e); } if (portablePdbStreamOpt != null) { var portablePdbBuilder = GetPortablePdbBuilder( typeSystemRowCounts, debugEntryPoint: default(MethodDefinitionHandle), deterministicIdProviderOpt: null); var portablePdbBlob = new BlobBuilder(); portablePdbBuilder.Serialize(portablePdbBlob); try { portablePdbBlob.WriteContentTo(portablePdbStreamOpt); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new SymUnmanagedWriterException(e.Message, e); } } } public void BuildMetadataAndIL( PdbWriter nativePdbWriterOpt, BlobBuilder ilBuilder, BlobBuilder mappedFieldDataBuilder, BlobBuilder managedResourceDataBuilder, out Blob mvidFixup, out Blob mvidStringFixup) { // Extract information from object model into tables, indices and streams CreateIndices(); if (_debugMetadataOpt != null) { // Ensure document table lists files in command line order // This is key for us to be able to accurately rebuild a binary from a PDB. var documentsBuilder = Module.DebugDocumentsBuilder; foreach (var tree in Module.CommonCompilation.SyntaxTrees) { if (documentsBuilder.TryGetDebugDocument(tree.FilePath, basePath: null) is { } doc && !_documentIndex.ContainsKey(doc)) { AddDocument(doc, _documentIndex); } } if (Context.RebuildData is { } rebuildData) { _usingNonSourceDocumentNameEnumerator = true; _nonSourceDocumentNameEnumerator = rebuildData.NonSourceFileDocumentNames.GetEnumerator(); } DefineModuleImportScope(); if (module.SourceLinkStreamOpt != null) { EmbedSourceLink(module.SourceLinkStreamOpt); } EmbedCompilationOptions(module); EmbedMetadataReferenceInformation(module); } int[] methodBodyOffsets; if (MetadataOnly) { methodBodyOffsets = SerializeThrowNullMethodBodies(ilBuilder); mvidStringFixup = default(Blob); } else { methodBodyOffsets = SerializeMethodBodies(ilBuilder, nativePdbWriterOpt, out mvidStringFixup); } _cancellationToken.ThrowIfCancellationRequested(); // method body serialization adds Stand Alone Signatures _tableIndicesAreComplete = true; ReportReferencesToAddedSymbols(); BlobBuilder dynamicAnalysisDataOpt = null; if (_dynamicAnalysisDataWriterOpt != null) { dynamicAnalysisDataOpt = new BlobBuilder(); _dynamicAnalysisDataWriterOpt.SerializeMetadataTables(dynamicAnalysisDataOpt); } PopulateTypeSystemTables(methodBodyOffsets, mappedFieldDataBuilder, managedResourceDataBuilder, dynamicAnalysisDataOpt, out mvidFixup); } public virtual void PopulateEncTables(ImmutableArray<int> typeSystemRowCounts) { } public MetadataRootBuilder GetRootBuilder() { // TODO (https://github.com/dotnet/roslyn/issues/3905): // InterfaceImpl table emitted by Roslyn is not compliant with ECMA spec. // Once fixed enable validation in DEBUG builds. return new MetadataRootBuilder(metadata, module.SerializationProperties.TargetRuntimeVersion, suppressValidation: true); } public PortablePdbBuilder GetPortablePdbBuilder(ImmutableArray<int> typeSystemRowCounts, MethodDefinitionHandle debugEntryPoint, Func<IEnumerable<Blob>, BlobContentId> deterministicIdProviderOpt) { return new PortablePdbBuilder(_debugMetadataOpt, typeSystemRowCounts, debugEntryPoint, deterministicIdProviderOpt); } internal void GetEntryPoints(out MethodDefinitionHandle entryPointHandle, out MethodDefinitionHandle debugEntryPointHandle) { if (IsFullMetadata && !MetadataOnly) { // PE entry point is set for executable programs IMethodReference entryPoint = module.PEEntryPoint; entryPointHandle = entryPoint != null ? (MethodDefinitionHandle)GetMethodHandle((IMethodDefinition)entryPoint.AsDefinition(Context)) : default(MethodDefinitionHandle); // debug entry point may be different from PE entry point, it may also be set for libraries IMethodReference debugEntryPoint = module.DebugEntryPoint; if (debugEntryPoint != null && debugEntryPoint != entryPoint) { debugEntryPointHandle = (MethodDefinitionHandle)GetMethodHandle((IMethodDefinition)debugEntryPoint.AsDefinition(Context)); } else { debugEntryPointHandle = entryPointHandle; } } else { entryPointHandle = debugEntryPointHandle = default(MethodDefinitionHandle); } } private ImmutableArray<IGenericParameter> GetSortedGenericParameters() { return GetGenericParameters().OrderBy((x, y) => { // Spec: GenericParam table is sorted by Owner and then by Number. int result = CodedIndex.TypeOrMethodDef(GetDeclaringTypeOrMethodHandle(x)) - CodedIndex.TypeOrMethodDef(GetDeclaringTypeOrMethodHandle(y)); if (result != 0) { return result; } return x.Index - y.Index; }).ToImmutableArray(); } private void PopulateTypeSystemTables(int[] methodBodyOffsets, BlobBuilder mappedFieldDataWriter, BlobBuilder resourceWriter, BlobBuilder dynamicAnalysisDataOpt, out Blob mvidFixup) { var sortedGenericParameters = GetSortedGenericParameters(); this.PopulateAssemblyRefTableRows(); this.PopulateAssemblyTableRows(); this.PopulateClassLayoutTableRows(); this.PopulateConstantTableRows(); this.PopulateDeclSecurityTableRows(); this.PopulateEventMapTableRows(); this.PopulateEventTableRows(); this.PopulateExportedTypeTableRows(); this.PopulateFieldLayoutTableRows(); this.PopulateFieldMarshalTableRows(); this.PopulateFieldRvaTableRows(mappedFieldDataWriter); this.PopulateFieldTableRows(); this.PopulateFileTableRows(); this.PopulateGenericParameters(sortedGenericParameters); this.PopulateImplMapTableRows(); this.PopulateInterfaceImplTableRows(); this.PopulateManifestResourceTableRows(resourceWriter, dynamicAnalysisDataOpt); this.PopulateMemberRefTableRows(); this.PopulateMethodImplTableRows(); this.PopulateMethodTableRows(methodBodyOffsets); this.PopulateMethodSemanticsTableRows(); this.PopulateMethodSpecTableRows(); this.PopulateModuleRefTableRows(); this.PopulateModuleTableRow(out mvidFixup); this.PopulateNestedClassTableRows(); this.PopulateParamTableRows(); this.PopulatePropertyMapTableRows(); this.PopulatePropertyTableRows(); this.PopulateTypeDefTableRows(); this.PopulateTypeRefTableRows(); this.PopulateTypeSpecTableRows(); this.PopulateStandaloneSignatures(); // This table is populated after the others because it depends on the order of the entries of the generic parameter table. this.PopulateCustomAttributeTableRows(sortedGenericParameters); } private void PopulateAssemblyRefTableRows() { var assemblyRefs = this.GetAssemblyRefs(); metadata.SetCapacity(TableIndex.AssemblyRef, assemblyRefs.Count); foreach (var identity in assemblyRefs) { // reference has token, not full public key metadata.AddAssemblyReference( name: GetStringHandleForPathAndCheckLength(identity.Name), version: identity.Version, culture: metadata.GetOrAddString(identity.CultureName), publicKeyOrToken: metadata.GetOrAddBlob(identity.PublicKeyToken), flags: (AssemblyFlags)((int)identity.ContentType << 9) | (identity.IsRetargetable ? AssemblyFlags.Retargetable : 0), hashValue: default(BlobHandle)); } } private void PopulateAssemblyTableRows() { if (!EmitAssemblyDefinition) { return; } var sourceAssembly = module.SourceAssemblyOpt; Debug.Assert(sourceAssembly != null); var flags = sourceAssembly.AssemblyFlags & ~AssemblyFlags.PublicKey; if (!sourceAssembly.Identity.PublicKey.IsDefaultOrEmpty) { flags |= AssemblyFlags.PublicKey; } metadata.AddAssembly( flags: flags, hashAlgorithm: sourceAssembly.HashAlgorithm, version: sourceAssembly.Identity.Version, publicKey: metadata.GetOrAddBlob(sourceAssembly.Identity.PublicKey), name: GetStringHandleForPathAndCheckLength(module.Name, module), culture: metadata.GetOrAddString(sourceAssembly.Identity.CultureName)); } private void PopulateCustomAttributeTableRows(ImmutableArray<IGenericParameter> sortedGenericParameters) { if (this.IsFullMetadata) { this.AddAssemblyAttributesToTable(); } this.AddCustomAttributesToTable(GetMethodDefs(), def => GetMethodDefinitionHandle(def)); this.AddCustomAttributesToTable(GetFieldDefs(), def => GetFieldDefinitionHandle(def)); // this.AddCustomAttributesToTable(this.typeRefList, 2); var typeDefs = GetTypeDefs(); this.AddCustomAttributesToTable(typeDefs, def => GetTypeDefinitionHandle(def)); this.AddCustomAttributesToTable(GetParameterDefs(), def => GetParameterHandle(def)); // TODO: attributes on member reference entries 6 if (this.IsFullMetadata) { this.AddModuleAttributesToTable(module); } // TODO: declarative security entries 8 this.AddCustomAttributesToTable(GetPropertyDefs(), def => GetPropertyDefIndex(def)); this.AddCustomAttributesToTable(GetEventDefs(), def => GetEventDefinitionHandle(def)); // TODO: standalone signature entries 11 // TODO: type spec entries 13 // this.AddCustomAttributesToTable(this.module.AssemblyReferences, 15); // TODO: this.AddCustomAttributesToTable(assembly.Files, 16); // TODO: exported types 17 // TODO: this.AddCustomAttributesToTable(assembly.Resources, 18); this.AddCustomAttributesToTable(sortedGenericParameters, TableIndex.GenericParam); } private void AddAssemblyAttributesToTable() { bool writingNetModule = module.OutputKind == OutputKind.NetModule; if (writingNetModule) { // When writing netmodules, assembly security attributes are not emitted by PopulateDeclSecurityTableRows(). // Instead, here we make sure they are emitted as regular attributes, attached off the appropriate placeholder // System.Runtime.CompilerServices.AssemblyAttributesGoHere* type refs. This is the contract for publishing // assembly attributes in netmodules so they may be migrated to containing/referencing multi-module assemblies, // at multi-module assembly build time. AddAssemblyAttributesToTable( this.module.GetSourceAssemblySecurityAttributes().Select(sa => sa.Attribute), needsDummyParent: true, isSecurity: true); } AddAssemblyAttributesToTable( this.module.GetSourceAssemblyAttributes(Context.IsRefAssembly), needsDummyParent: writingNetModule, isSecurity: false); } private void AddAssemblyAttributesToTable(IEnumerable<ICustomAttribute> assemblyAttributes, bool needsDummyParent, bool isSecurity) { Debug.Assert(this.IsFullMetadata); // parentToken is not relative EntityHandle parentHandle = Handle.AssemblyDefinition; foreach (ICustomAttribute customAttribute in assemblyAttributes) { if (needsDummyParent) { // When writing netmodules, assembly attributes are attached off the appropriate placeholder // System.Runtime.CompilerServices.AssemblyAttributesGoHere* type refs. This is the contract for publishing // assembly attributes in netmodules so they may be migrated to containing/referencing multi-module assemblies, // at multi-module assembly build time. parentHandle = GetDummyAssemblyAttributeParent(isSecurity, customAttribute.AllowMultiple); } AddCustomAttributeToTable(parentHandle, customAttribute); } } private TypeReferenceHandle GetDummyAssemblyAttributeParent(bool isSecurity, bool allowMultiple) { // Lazily get or create placeholder assembly attribute parent type ref for the given combination of // whether isSecurity and allowMultiple. Convert type ref row id to corresponding attribute parent tag. // Note that according to the defacto contract, although the placeholder type refs have CorLibrary as their // resolution scope, the types backing the placeholder type refs need not actually exist. int iS = isSecurity ? 1 : 0; int iM = allowMultiple ? 1 : 0; if (_dummyAssemblyAttributeParent[iS, iM].IsNil) { _dummyAssemblyAttributeParent[iS, iM] = metadata.AddTypeReference( resolutionScope: GetResolutionScopeHandle(module.GetCorLibrary(Context)), @namespace: metadata.GetOrAddString(dummyAssemblyAttributeParentNamespace), name: metadata.GetOrAddString(dummyAssemblyAttributeParentName + dummyAssemblyAttributeParentQualifier[iS, iM])); } return _dummyAssemblyAttributeParent[iS, iM]; } private void AddModuleAttributesToTable(CommonPEModuleBuilder module) { Debug.Assert(this.IsFullMetadata); AddCustomAttributesToTable(EntityHandle.ModuleDefinition, module.GetSourceModuleAttributes()); } private void AddCustomAttributesToTable<T>(IEnumerable<T> parentList, TableIndex tableIndex) where T : IReference { int parentRowId = 1; foreach (var parent in parentList) { var parentHandle = MetadataTokens.Handle(tableIndex, parentRowId++); AddCustomAttributesToTable(parentHandle, parent.GetAttributes(Context)); } } private void AddCustomAttributesToTable<T>(IEnumerable<T> parentList, Func<T, EntityHandle> getDefinitionHandle) where T : IReference { foreach (var parent in parentList) { EntityHandle parentHandle = getDefinitionHandle(parent); AddCustomAttributesToTable(parentHandle, parent.GetAttributes(Context)); } } protected virtual int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable<ICustomAttribute> attributes) { int count = 0; foreach (var attr in attributes) { count++; AddCustomAttributeToTable(parentHandle, attr); } return count; } private void AddCustomAttributeToTable(EntityHandle parentHandle, ICustomAttribute customAttribute) { IMethodReference constructor = customAttribute.Constructor(Context, reportDiagnostics: true); if (constructor != null) { metadata.AddCustomAttribute( parent: parentHandle, constructor: GetCustomAttributeTypeCodedIndex(constructor), value: GetCustomAttributeSignatureIndex(customAttribute)); } } private void PopulateDeclSecurityTableRows() { if (module.OutputKind != OutputKind.NetModule) { this.PopulateDeclSecurityTableRowsFor(EntityHandle.AssemblyDefinition, module.GetSourceAssemblySecurityAttributes()); } foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { if (!typeDef.HasDeclarativeSecurity) { continue; } this.PopulateDeclSecurityTableRowsFor(GetTypeDefinitionHandle(typeDef), typeDef.SecurityAttributes); } foreach (IMethodDefinition methodDef in this.GetMethodDefs()) { if (!methodDef.HasDeclarativeSecurity) { continue; } this.PopulateDeclSecurityTableRowsFor(GetMethodDefinitionHandle(methodDef), methodDef.SecurityAttributes); } } private void PopulateDeclSecurityTableRowsFor(EntityHandle parentHandle, IEnumerable<SecurityAttribute> attributes) { OrderPreservingMultiDictionary<DeclarativeSecurityAction, ICustomAttribute> groupedSecurityAttributes = null; foreach (SecurityAttribute securityAttribute in attributes) { groupedSecurityAttributes = groupedSecurityAttributes ?? OrderPreservingMultiDictionary<DeclarativeSecurityAction, ICustomAttribute>.GetInstance(); groupedSecurityAttributes.Add(securityAttribute.Action, securityAttribute.Attribute); } if (groupedSecurityAttributes == null) { return; } foreach (DeclarativeSecurityAction securityAction in groupedSecurityAttributes.Keys) { metadata.AddDeclarativeSecurityAttribute( parent: parentHandle, action: securityAction, permissionSet: GetPermissionSetBlobHandle(groupedSecurityAttributes[securityAction])); } groupedSecurityAttributes.Free(); } private void PopulateEventTableRows() { var eventDefs = this.GetEventDefs(); metadata.SetCapacity(TableIndex.Event, eventDefs.Count); foreach (IEventDefinition eventDef in eventDefs) { metadata.AddEvent( attributes: GetEventAttributes(eventDef), name: GetStringHandleForNameAndCheckLength(eventDef.Name, eventDef), type: GetTypeHandle(eventDef.GetType(Context))); } } private void PopulateExportedTypeTableRows() { if (!IsFullMetadata) { return; } var exportedTypes = module.GetExportedTypes(Context.Diagnostics); if (exportedTypes.Length == 0) { return; } metadata.SetCapacity(TableIndex.ExportedType, exportedTypes.Length); foreach (var exportedType in exportedTypes) { INestedTypeReference nestedRef; INamespaceTypeReference namespaceTypeRef; TypeAttributes attributes; StringHandle typeName; StringHandle typeNamespace; EntityHandle implementation; if ((namespaceTypeRef = exportedType.Type.AsNamespaceTypeReference) != null) { // exported types are not emitted in EnC deltas (hence generation 0): string mangledTypeName = GetMangledName(namespaceTypeRef, generation: 0); typeName = GetStringHandleForNameAndCheckLength(mangledTypeName, namespaceTypeRef); typeNamespace = GetStringHandleForNamespaceAndCheckLength(namespaceTypeRef, mangledTypeName); implementation = GetExportedTypeImplementation(namespaceTypeRef); attributes = exportedType.IsForwarder ? TypeAttributes.NotPublic | Constants.TypeAttributes_TypeForwarder : TypeAttributes.Public; } else if ((nestedRef = exportedType.Type.AsNestedTypeReference) != null) { Debug.Assert(exportedType.ParentIndex != -1); // exported types are not emitted in EnC deltas (hence generation 0): string mangledTypeName = GetMangledName(nestedRef, generation: 0); typeName = GetStringHandleForNameAndCheckLength(mangledTypeName, nestedRef); typeNamespace = default(StringHandle); implementation = MetadataTokens.ExportedTypeHandle(exportedType.ParentIndex + 1); attributes = exportedType.IsForwarder ? TypeAttributes.NotPublic : TypeAttributes.NestedPublic; } else { throw ExceptionUtilities.UnexpectedValue(exportedType); } metadata.AddExportedType( attributes: attributes, @namespace: typeNamespace, name: typeName, implementation: implementation, typeDefinitionId: exportedType.IsForwarder ? 0 : MetadataTokens.GetToken(exportedType.Type.TypeDef)); } } private void PopulateFieldLayoutTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (fieldDef.ContainingTypeDefinition.Layout != LayoutKind.Explicit || fieldDef.IsStatic) { continue; } metadata.AddFieldLayout( field: GetFieldDefinitionHandle(fieldDef), offset: fieldDef.Offset); } } private void PopulateFieldMarshalTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (!fieldDef.IsMarshalledExplicitly) { continue; } var marshallingInformation = fieldDef.MarshallingInformation; BlobHandle descriptor = (marshallingInformation != null) ? GetMarshallingDescriptorHandle(marshallingInformation) : GetMarshallingDescriptorHandle(fieldDef.MarshallingDescriptor); metadata.AddMarshallingDescriptor( parent: GetFieldDefinitionHandle(fieldDef), descriptor: descriptor); } foreach (IParameterDefinition parDef in this.GetParameterDefs()) { if (!parDef.IsMarshalledExplicitly) { continue; } var marshallingInformation = parDef.MarshallingInformation; BlobHandle descriptor = (marshallingInformation != null) ? GetMarshallingDescriptorHandle(marshallingInformation) : GetMarshallingDescriptorHandle(parDef.MarshallingDescriptor); metadata.AddMarshallingDescriptor( parent: GetParameterHandle(parDef), descriptor: descriptor); } } private void PopulateFieldRvaTableRows(BlobBuilder mappedFieldDataWriter) { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (fieldDef.MappedData.IsDefault) { continue; } int offset = mappedFieldDataWriter.Count; mappedFieldDataWriter.WriteBytes(fieldDef.MappedData); mappedFieldDataWriter.Align(ManagedPEBuilder.MappedFieldDataAlignment); metadata.AddFieldRelativeVirtualAddress( field: GetFieldDefinitionHandle(fieldDef), offset: offset); } } private void PopulateFieldTableRows() { var fieldDefs = this.GetFieldDefs(); metadata.SetCapacity(TableIndex.Field, fieldDefs.Count); foreach (IFieldDefinition fieldDef in fieldDefs) { if (fieldDef.IsContextualNamedEntity) { ((IContextualNamedEntity)fieldDef).AssociateWithMetadataWriter(this); } metadata.AddFieldDefinition( attributes: GetFieldAttributes(fieldDef), name: GetStringHandleForNameAndCheckLength(fieldDef.Name, fieldDef), signature: GetFieldSignatureIndex(fieldDef)); } } private void PopulateConstantTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { var constant = fieldDef.GetCompileTimeValue(Context); if (constant == null) { continue; } metadata.AddConstant( parent: GetFieldDefinitionHandle(fieldDef), value: constant.Value); } foreach (IParameterDefinition parDef in this.GetParameterDefs()) { var defaultValue = parDef.GetDefaultValue(Context); if (defaultValue == null) { continue; } metadata.AddConstant( parent: GetParameterHandle(parDef), value: defaultValue.Value); } foreach (IPropertyDefinition propDef in this.GetPropertyDefs()) { if (!propDef.HasDefaultValue) { continue; } metadata.AddConstant( parent: GetPropertyDefIndex(propDef), value: propDef.DefaultValue.Value); } } private void PopulateFileTableRows() { ISourceAssemblySymbolInternal assembly = module.SourceAssemblyOpt; if (assembly == null) { return; } var hashAlgorithm = assembly.HashAlgorithm; metadata.SetCapacity(TableIndex.File, _fileRefList.Count); foreach (IFileReference fileReference in _fileRefList) { metadata.AddAssemblyFile( name: GetStringHandleForPathAndCheckLength(fileReference.FileName), hashValue: metadata.GetOrAddBlob(fileReference.GetHashValue(hashAlgorithm)), containsMetadata: fileReference.HasMetadata); } } private void PopulateGenericParameters( ImmutableArray<IGenericParameter> sortedGenericParameters) { foreach (IGenericParameter genericParameter in sortedGenericParameters) { // CONSIDER: The CLI spec doesn't mention a restriction on the Name column of the GenericParam table, // but they go in the same string heap as all the other declaration names, so it stands to reason that // they should be restricted in the same way. var genericParameterHandle = metadata.AddGenericParameter( parent: GetDeclaringTypeOrMethodHandle(genericParameter), attributes: GetGenericParameterAttributes(genericParameter), name: GetStringHandleForNameAndCheckLength(genericParameter.Name, genericParameter), index: genericParameter.Index); foreach (var refWithAttributes in genericParameter.GetConstraints(Context)) { var genericConstraintHandle = metadata.AddGenericParameterConstraint( genericParameter: genericParameterHandle, constraint: GetTypeHandle(refWithAttributes.TypeRef)); AddCustomAttributesToTable(genericConstraintHandle, refWithAttributes.Attributes); } } } private void PopulateImplMapTableRows() { foreach (IMethodDefinition methodDef in this.GetMethodDefs()) { if (!methodDef.IsPlatformInvoke) { continue; } var data = methodDef.PlatformInvokeData; string entryPointName = data.EntryPointName; StringHandle importName = entryPointName != null && entryPointName != methodDef.Name ? GetStringHandleForNameAndCheckLength(entryPointName, methodDef) : metadata.GetOrAddString(methodDef.Name); // Length checked while populating the method def table. metadata.AddMethodImport( method: GetMethodDefinitionHandle(methodDef), attributes: data.Flags, name: importName, module: GetModuleReferenceHandle(data.ModuleName)); } } private void PopulateInterfaceImplTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { var typeDefHandle = GetTypeDefinitionHandle(typeDef); foreach (var interfaceImpl in typeDef.Interfaces(Context)) { var handle = metadata.AddInterfaceImplementation( type: typeDefHandle, implementedInterface: GetTypeHandle(interfaceImpl.TypeRef)); AddCustomAttributesToTable(handle, interfaceImpl.Attributes); } } } private void PopulateManifestResourceTableRows(BlobBuilder resourceDataWriter, BlobBuilder dynamicAnalysisDataOpt) { if (dynamicAnalysisDataOpt != null) { metadata.AddManifestResource( attributes: ManifestResourceAttributes.Private, name: metadata.GetOrAddString("<DynamicAnalysisData>"), implementation: default(EntityHandle), offset: GetManagedResourceOffset(dynamicAnalysisDataOpt, resourceDataWriter) ); } foreach (var resource in this.module.GetResources(Context)) { EntityHandle implementation; if (resource.ExternalFile != null) { // Length checked on insertion into the file table. implementation = GetAssemblyFileHandle(resource.ExternalFile); } else { // This is an embedded resource, we don't support references to resources from referenced assemblies. implementation = default(EntityHandle); } metadata.AddManifestResource( attributes: resource.IsPublic ? ManifestResourceAttributes.Public : ManifestResourceAttributes.Private, name: GetStringHandleForNameAndCheckLength(resource.Name), implementation: implementation, offset: GetManagedResourceOffset(resource, resourceDataWriter)); } // the stream should be aligned: Debug.Assert((resourceDataWriter.Count % ManagedPEBuilder.ManagedResourcesDataAlignment) == 0); } private void PopulateMemberRefTableRows() { var memberRefs = this.GetMemberRefs(); metadata.SetCapacity(TableIndex.MemberRef, memberRefs.Count); foreach (ITypeMemberReference memberRef in memberRefs) { metadata.AddMemberReference( parent: GetMemberReferenceParent(memberRef), name: GetStringHandleForNameAndCheckLength(memberRef.Name, memberRef), signature: GetMemberReferenceSignatureHandle(memberRef)); } } private void PopulateMethodImplTableRows() { metadata.SetCapacity(TableIndex.MethodImpl, methodImplList.Count); foreach (MethodImplementation methodImplementation in this.methodImplList) { metadata.AddMethodImplementation( type: GetTypeDefinitionHandle(methodImplementation.ContainingType), methodBody: GetMethodDefinitionOrReferenceHandle(methodImplementation.ImplementingMethod), methodDeclaration: GetMethodDefinitionOrReferenceHandle(methodImplementation.ImplementedMethod)); } } private void PopulateMethodSpecTableRows() { var methodSpecs = this.GetMethodSpecs(); metadata.SetCapacity(TableIndex.MethodSpec, methodSpecs.Count); foreach (IGenericMethodInstanceReference genericMethodInstanceReference in methodSpecs) { metadata.AddMethodSpecification( method: GetMethodDefinitionOrReferenceHandle(genericMethodInstanceReference.GetGenericMethod(Context)), instantiation: GetMethodSpecificationBlobHandle(genericMethodInstanceReference)); } } private void PopulateMethodTableRows(int[] methodBodyOffsets) { var methodDefs = this.GetMethodDefs(); metadata.SetCapacity(TableIndex.MethodDef, methodDefs.Count); int i = 0; foreach (IMethodDefinition methodDef in methodDefs) { metadata.AddMethodDefinition( attributes: GetMethodAttributes(methodDef), implAttributes: methodDef.GetImplementationAttributes(Context), name: GetStringHandleForNameAndCheckLength(methodDef.Name, methodDef), signature: GetMethodSignatureHandle(methodDef), bodyOffset: methodBodyOffsets[i], parameterList: GetFirstParameterHandle(methodDef)); i++; } } private void PopulateMethodSemanticsTableRows() { var propertyDefs = this.GetPropertyDefs(); var eventDefs = this.GetEventDefs(); // an estimate, not necessarily accurate. metadata.SetCapacity(TableIndex.MethodSemantics, propertyDefs.Count * 2 + eventDefs.Count * 2); foreach (IPropertyDefinition propertyDef in this.GetPropertyDefs()) { var association = GetPropertyDefIndex(propertyDef); foreach (IMethodReference accessorMethod in propertyDef.GetAccessors(Context)) { MethodSemanticsAttributes semantics; if (accessorMethod == propertyDef.Setter) { semantics = MethodSemanticsAttributes.Setter; } else if (accessorMethod == propertyDef.Getter) { semantics = MethodSemanticsAttributes.Getter; } else { semantics = MethodSemanticsAttributes.Other; } metadata.AddMethodSemantics( association: association, semantics: semantics, methodDefinition: GetMethodDefinitionHandle(accessorMethod.GetResolvedMethod(Context))); } } foreach (IEventDefinition eventDef in this.GetEventDefs()) { var association = GetEventDefinitionHandle(eventDef); foreach (IMethodReference accessorMethod in eventDef.GetAccessors(Context)) { MethodSemanticsAttributes semantics; if (accessorMethod == eventDef.Adder) { semantics = MethodSemanticsAttributes.Adder; } else if (accessorMethod == eventDef.Remover) { semantics = MethodSemanticsAttributes.Remover; } else if (accessorMethod == eventDef.Caller) { semantics = MethodSemanticsAttributes.Raiser; } else { semantics = MethodSemanticsAttributes.Other; } metadata.AddMethodSemantics( association: association, semantics: semantics, methodDefinition: GetMethodDefinitionHandle(accessorMethod.GetResolvedMethod(Context))); } } } private void PopulateModuleRefTableRows() { var moduleRefs = this.GetModuleRefs(); metadata.SetCapacity(TableIndex.ModuleRef, moduleRefs.Count); foreach (string moduleName in moduleRefs) { metadata.AddModuleReference(GetStringHandleForPathAndCheckLength(moduleName)); } } private void PopulateModuleTableRow(out Blob mvidFixup) { CheckPathLength(this.module.ModuleName); GuidHandle mvidHandle; Guid mvid = this.module.SerializationProperties.PersistentIdentifier; if (mvid != default(Guid)) { // MVID is specified upfront when emitting EnC delta: mvidHandle = metadata.GetOrAddGuid(mvid); mvidFixup = default(Blob); } else { // The guid will be filled in later: var reservedGuid = metadata.ReserveGuid(); mvidFixup = reservedGuid.Content; mvidHandle = reservedGuid.Handle; reservedGuid.CreateWriter().WriteBytes(0, mvidFixup.Length); } metadata.AddModule( generation: this.Generation, moduleName: metadata.GetOrAddString(this.module.ModuleName), mvid: mvidHandle, encId: metadata.GetOrAddGuid(EncId), encBaseId: metadata.GetOrAddGuid(EncBaseId)); } private void PopulateParamTableRows() { var parameterDefs = this.GetParameterDefs(); metadata.SetCapacity(TableIndex.Param, parameterDefs.Count); foreach (IParameterDefinition parDef in parameterDefs) { metadata.AddParameter( attributes: GetParameterAttributes(parDef), sequenceNumber: (parDef is ReturnValueParameter) ? 0 : parDef.Index + 1, name: GetStringHandleForNameAndCheckLength(parDef.Name, parDef)); } } private void PopulatePropertyTableRows() { var propertyDefs = this.GetPropertyDefs(); metadata.SetCapacity(TableIndex.Property, propertyDefs.Count); foreach (IPropertyDefinition propertyDef in propertyDefs) { metadata.AddProperty( attributes: GetPropertyAttributes(propertyDef), name: GetStringHandleForNameAndCheckLength(propertyDef.Name, propertyDef), signature: GetPropertySignatureHandle(propertyDef)); } } private void PopulateTypeDefTableRows() { var typeDefs = this.GetTypeDefs(); metadata.SetCapacity(TableIndex.TypeDef, typeDefs.Count); foreach (INamedTypeDefinition typeDef in typeDefs) { INamespaceTypeDefinition namespaceType = typeDef.AsNamespaceTypeDefinition(Context); var moduleBuilder = Context.Module; int generation = moduleBuilder.GetTypeDefinitionGeneration(typeDef); string mangledTypeName = GetMangledName(typeDef, generation); ITypeReference baseType = typeDef.GetBaseClass(Context); metadata.AddTypeDefinition( attributes: GetTypeAttributes(typeDef), @namespace: (namespaceType != null) ? GetStringHandleForNamespaceAndCheckLength(namespaceType, mangledTypeName) : default(StringHandle), name: GetStringHandleForNameAndCheckLength(mangledTypeName, typeDef), baseType: (baseType != null) ? GetTypeHandle(baseType) : default(EntityHandle), fieldList: GetFirstFieldDefinitionHandle(typeDef), methodList: GetFirstMethodDefinitionHandle(typeDef)); } } private void PopulateNestedClassTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef == null) { continue; } metadata.AddNestedType( type: GetTypeDefinitionHandle(typeDef), enclosingType: GetTypeDefinitionHandle(nestedTypeDef.ContainingTypeDefinition)); } } private void PopulateClassLayoutTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { if (typeDef.Alignment == 0 && typeDef.SizeOf == 0) { continue; } metadata.AddTypeLayout( type: GetTypeDefinitionHandle(typeDef), packingSize: typeDef.Alignment, size: typeDef.SizeOf); } } private void PopulateTypeRefTableRows() { var typeRefs = this.GetTypeRefs(); metadata.SetCapacity(TableIndex.TypeRef, typeRefs.Count); foreach (ITypeReference typeRef in typeRefs) { EntityHandle resolutionScope; StringHandle name; StringHandle @namespace; INestedTypeReference nestedTypeRef = typeRef.AsNestedTypeReference; if (nestedTypeRef != null) { ITypeReference scopeTypeRef; ISpecializedNestedTypeReference sneTypeRef = nestedTypeRef.AsSpecializedNestedTypeReference; if (sneTypeRef != null) { scopeTypeRef = sneTypeRef.GetUnspecializedVersion(Context).GetContainingType(Context); } else { scopeTypeRef = nestedTypeRef.GetContainingType(Context); } resolutionScope = GetTypeReferenceHandle(scopeTypeRef); // It's not possible to reference newer versions of reloadable types from another assembly, hence generation 0: // TODO: https://github.com/dotnet/roslyn/issues/54981 string mangledTypeName = GetMangledName(nestedTypeRef, generation: 0); name = this.GetStringHandleForNameAndCheckLength(mangledTypeName, nestedTypeRef); @namespace = default(StringHandle); } else { INamespaceTypeReference namespaceTypeRef = typeRef.AsNamespaceTypeReference; if (namespaceTypeRef == null) { throw ExceptionUtilities.UnexpectedValue(typeRef); } resolutionScope = this.GetResolutionScopeHandle(namespaceTypeRef.GetUnit(Context)); // It's not possible to reference newer versions of reloadable types from another assembly, hence generation 0: // TODO: https://github.com/dotnet/roslyn/issues/54981 string mangledTypeName = GetMangledName(namespaceTypeRef, generation: 0); name = this.GetStringHandleForNameAndCheckLength(mangledTypeName, namespaceTypeRef); @namespace = this.GetStringHandleForNamespaceAndCheckLength(namespaceTypeRef, mangledTypeName); } metadata.AddTypeReference( resolutionScope: resolutionScope, @namespace: @namespace, name: name); } } private void PopulateTypeSpecTableRows() { var typeSpecs = this.GetTypeSpecs(); metadata.SetCapacity(TableIndex.TypeSpec, typeSpecs.Count); foreach (ITypeReference typeSpec in typeSpecs) { metadata.AddTypeSpecification(GetTypeSpecSignatureIndex(typeSpec)); } } private void PopulateStandaloneSignatures() { var signatures = GetStandaloneSignatureBlobHandles(); foreach (BlobHandle signature in signatures) { metadata.AddStandaloneSignature(signature); } } private int[] SerializeThrowNullMethodBodies(BlobBuilder ilBuilder) { Debug.Assert(MetadataOnly); var methods = this.GetMethodDefs(); int[] bodyOffsets = new int[methods.Count]; int bodyOffsetCache = -1; int methodRid = 0; foreach (IMethodDefinition method in methods) { if (method.HasBody()) { if (bodyOffsetCache == -1) { bodyOffsetCache = ilBuilder.Count; ilBuilder.WriteBytes(ThrowNullEncodedBody); } bodyOffsets[methodRid] = bodyOffsetCache; } else { bodyOffsets[methodRid] = -1; } methodRid++; } return bodyOffsets; } private int[] SerializeMethodBodies(BlobBuilder ilBuilder, PdbWriter nativePdbWriterOpt, out Blob mvidStringFixup) { CustomDebugInfoWriter customDebugInfoWriter = (nativePdbWriterOpt != null) ? new CustomDebugInfoWriter(nativePdbWriterOpt) : null; var methods = this.GetMethodDefs(); int[] bodyOffsets = new int[methods.Count]; var lastLocalVariableHandle = default(LocalVariableHandle); var lastLocalConstantHandle = default(LocalConstantHandle); var encoder = new MethodBodyStreamEncoder(ilBuilder); var mvidStringHandle = default(UserStringHandle); mvidStringFixup = default(Blob); int methodRid = 1; foreach (IMethodDefinition method in methods) { _cancellationToken.ThrowIfCancellationRequested(); int bodyOffset; IMethodBody body; StandaloneSignatureHandle localSignatureHandleOpt; if (method.HasBody()) { body = method.GetBody(Context); if (body != null) { localSignatureHandleOpt = this.SerializeLocalVariablesSignature(body); // TODO: consider parallelizing these (local signature tokens can be piped into IL serialization & debug info generation) bodyOffset = SerializeMethodBody(encoder, body, localSignatureHandleOpt, ref mvidStringHandle, ref mvidStringFixup); nativePdbWriterOpt?.SerializeDebugInfo(body, localSignatureHandleOpt, customDebugInfoWriter); } else { bodyOffset = 0; localSignatureHandleOpt = default(StandaloneSignatureHandle); } } else { // 0 is actually written to metadata when the row is serialized bodyOffset = -1; body = null; localSignatureHandleOpt = default(StandaloneSignatureHandle); } if (_debugMetadataOpt != null) { // methodRid is based on this delta but for async state machine debug info we need the "real" row number // of the method aggregated across generations var aggregateMethodRid = MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(method)); SerializeMethodDebugInfo(body, methodRid, aggregateMethodRid, localSignatureHandleOpt, ref lastLocalVariableHandle, ref lastLocalConstantHandle); } _dynamicAnalysisDataWriterOpt?.SerializeMethodDynamicAnalysisData(body); bodyOffsets[methodRid - 1] = bodyOffset; methodRid++; } return bodyOffsets; } private int SerializeMethodBody(MethodBodyStreamEncoder encoder, IMethodBody methodBody, StandaloneSignatureHandle localSignatureHandleOpt, ref UserStringHandle mvidStringHandle, ref Blob mvidStringFixup) { int ilLength = methodBody.IL.Length; var exceptionRegions = methodBody.ExceptionRegions; bool isSmallBody = ilLength < 64 && methodBody.MaxStack <= 8 && localSignatureHandleOpt.IsNil && exceptionRegions.Length == 0; var smallBodyKey = (methodBody.IL, methodBody.AreLocalsZeroed); // Check if an identical method body has already been serialized. // If so, use the RVA of the already serialized one. // Note that we don't need to rewrite the fake tokens in the body before looking it up. // Don't do small body method caching during deterministic builds until this issue is fixed // https://github.com/dotnet/roslyn/issues/7595 int bodyOffset; if (!_deterministic && isSmallBody && _smallMethodBodies.TryGetValue(smallBodyKey, out bodyOffset)) { return bodyOffset; } var encodedBody = encoder.AddMethodBody( codeSize: methodBody.IL.Length, maxStack: methodBody.MaxStack, exceptionRegionCount: exceptionRegions.Length, hasSmallExceptionRegions: MayUseSmallExceptionHeaders(exceptionRegions), localVariablesSignature: localSignatureHandleOpt, attributes: (methodBody.AreLocalsZeroed ? MethodBodyAttributes.InitLocals : 0), hasDynamicStackAllocation: methodBody.HasStackalloc); // Don't do small body method caching during deterministic builds until this issue is fixed // https://github.com/dotnet/roslyn/issues/7595 if (isSmallBody && !_deterministic) { _smallMethodBodies.Add(smallBodyKey, encodedBody.Offset); } WriteInstructions(encodedBody.Instructions, methodBody.IL, ref mvidStringHandle, ref mvidStringFixup); SerializeMethodBodyExceptionHandlerTable(encodedBody.ExceptionRegions, exceptionRegions); return encodedBody.Offset; } /// <summary> /// Serialize the method local signature to the blob. /// </summary> /// <returns>Standalone signature token</returns> protected virtual StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body) { Debug.Assert(!_tableIndicesAreComplete); var localVariables = body.LocalVariables; if (localVariables.Length == 0) { return default(StandaloneSignatureHandle); } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).LocalVariableSignature(localVariables.Length); foreach (ILocalDefinition local in localVariables) { SerializeLocalVariableType(encoder.AddVariable(), local); } BlobHandle blobIndex = metadata.GetOrAddBlob(builder); var handle = GetOrAddStandaloneSignatureHandle(blobIndex); builder.Free(); return handle; } protected void SerializeLocalVariableType(LocalVariableTypeEncoder encoder, ILocalDefinition local) { if (local.CustomModifiers.Length > 0) { SerializeCustomModifiers(encoder.CustomModifiers(), local.CustomModifiers); } if (module.IsPlatformType(local.Type, PlatformType.SystemTypedReference)) { encoder.TypedReference(); return; } SerializeTypeReference(encoder.Type(local.IsReference, local.IsPinned), local.Type); } internal StandaloneSignatureHandle SerializeLocalConstantStandAloneSignature(ILocalDefinition localConstant) { var builder = PooledBlobBuilder.GetInstance(); var typeEncoder = new BlobEncoder(builder).FieldSignature(); if (localConstant.CustomModifiers.Length > 0) { SerializeCustomModifiers(typeEncoder.CustomModifiers(), localConstant.CustomModifiers); } SerializeTypeReference(typeEncoder, localConstant.Type); BlobHandle blobIndex = metadata.GetOrAddBlob(builder); var signatureHandle = GetOrAddStandaloneSignatureHandle(blobIndex); builder.Free(); return signatureHandle; } private static byte ReadByte(ImmutableArray<byte> buffer, int pos) { return buffer[pos]; } private static int ReadInt32(ImmutableArray<byte> buffer, int pos) { return buffer[pos] | buffer[pos + 1] << 8 | buffer[pos + 2] << 16 | buffer[pos + 3] << 24; } private EntityHandle GetHandle(object reference) { return reference switch { ITypeReference typeReference => GetTypeHandle(typeReference), IFieldReference fieldReference => GetFieldHandle(fieldReference), IMethodReference methodReference => GetMethodHandle(methodReference), ISignature signature => GetStandaloneSignatureHandle(signature), _ => throw ExceptionUtilities.UnexpectedValue(reference) }; } private EntityHandle ResolveEntityHandleFromPseudoToken(int pseudoSymbolToken) { int index = pseudoSymbolToken; var entity = _pseudoSymbolTokenToReferenceMap[index]; if (entity != null) { // EDMAURER since method bodies are not visited as they are in CCI, the operations // that would have been done on them are done here. if (entity is IReference reference) { _referenceVisitor.VisitMethodBodyReference(reference); } else if (entity is ISignature signature) { _referenceVisitor.VisitSignature(signature); } EntityHandle handle = GetHandle(entity); _pseudoSymbolTokenToTokenMap[index] = handle; _pseudoSymbolTokenToReferenceMap[index] = null; // Set to null to bypass next lookup return handle; } return _pseudoSymbolTokenToTokenMap[index]; } private UserStringHandle ResolveUserStringHandleFromPseudoToken(int pseudoStringToken) { int index = pseudoStringToken; var str = _pseudoStringTokenToStringMap[index]; if (str != null) { var handle = GetOrAddUserString(str); _pseudoStringTokenToTokenMap[index] = handle; _pseudoStringTokenToStringMap[index] = null; // Set to null to bypass next lookup return handle; } return _pseudoStringTokenToTokenMap[index]; } private UserStringHandle GetOrAddUserString(string str) { if (!_userStringTokenOverflow) { try { return metadata.GetOrAddUserString(str); } catch (ImageFormatLimitationException) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_TooManyUserStrings, NoLocation.Singleton)); _userStringTokenOverflow = true; } } return default(UserStringHandle); } private ReservedBlob<UserStringHandle> ReserveUserString(int length) { if (!_userStringTokenOverflow) { try { return metadata.ReserveUserString(length); } catch (ImageFormatLimitationException) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_TooManyUserStrings, NoLocation.Singleton)); _userStringTokenOverflow = true; } } return default(ReservedBlob<UserStringHandle>); } internal const uint LiteralMethodDefinitionToken = 0x80000000; internal const uint LiteralGreatestMethodDefinitionToken = 0x40000000; internal const uint SourceDocumentIndex = 0x20000000; internal const uint ModuleVersionIdStringToken = 0x80000000; private void WriteInstructions(Blob finalIL, ImmutableArray<byte> generatedIL, ref UserStringHandle mvidStringHandle, ref Blob mvidStringFixup) { // write the raw body first and then patch tokens: var writer = new BlobWriter(finalIL); writer.WriteBytes(generatedIL); writer.Offset = 0; int offset = 0; while (offset < generatedIL.Length) { var operandType = InstructionOperandTypes.ReadOperandType(generatedIL, ref offset); switch (operandType) { case OperandType.InlineField: case OperandType.InlineMethod: case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineSig: { int pseudoToken = ReadInt32(generatedIL, offset); int token = 0; // If any bits in the high-order byte of the pseudotoken are nonzero, replace the opcode with Ldc_i4 // and either clear the high-order byte in the pseudotoken or ignore the pseudotoken. // This is a trick to enable loading raw metadata token indices as integers. if (operandType == OperandType.InlineTok) { int tokenMask = pseudoToken & unchecked((int)0xff000000); if (tokenMask != 0 && (uint)pseudoToken != 0xffffffff) { Debug.Assert(ReadByte(generatedIL, offset - 1) == (byte)ILOpCode.Ldtoken); writer.Offset = offset - 1; writer.WriteByte((byte)ILOpCode.Ldc_i4); switch ((uint)tokenMask) { case LiteralMethodDefinitionToken: // Crash the compiler if pseudo token fails to resolve to a MethodDefinitionHandle. var handle = (MethodDefinitionHandle)ResolveEntityHandleFromPseudoToken(pseudoToken & 0x00ffffff); token = MetadataTokens.GetToken(handle) & 0x00ffffff; break; case LiteralGreatestMethodDefinitionToken: token = GreatestMethodDefIndex; break; case SourceDocumentIndex: token = _dynamicAnalysisDataWriterOpt.GetOrAddDocument(((CommonPEModuleBuilder)module).GetSourceDocumentFromIndex((uint)(pseudoToken & 0x00ffffff))); break; default: throw ExceptionUtilities.UnexpectedValue(tokenMask); } } } writer.Offset = offset; writer.WriteInt32(token == 0 ? MetadataTokens.GetToken(ResolveEntityHandleFromPseudoToken(pseudoToken)) : token); offset += 4; break; } case OperandType.InlineString: { writer.Offset = offset; int pseudoToken = ReadInt32(generatedIL, offset); UserStringHandle handle; if ((uint)pseudoToken == ModuleVersionIdStringToken) { // The pseudotoken encoding indicates that the string should refer to a textual encoding of the // current module's module version ID (such that the MVID can be realized using Guid.Parse). // The value cannot be determined until very late in the compilation, so reserve a slot for it now and fill in the value later. if (mvidStringHandle.IsNil) { const int guidStringLength = 36; Debug.Assert(guidStringLength == default(Guid).ToString().Length); var reserved = ReserveUserString(guidStringLength); mvidStringHandle = reserved.Handle; mvidStringFixup = reserved.Content; } handle = mvidStringHandle; } else { handle = ResolveUserStringHandleFromPseudoToken(pseudoToken); } writer.WriteInt32(MetadataTokens.GetToken(handle)); offset += 4; break; } case OperandType.InlineBrTarget: case OperandType.InlineI: case OperandType.ShortInlineR: offset += 4; break; case OperandType.InlineSwitch: int argCount = ReadInt32(generatedIL, offset); // skip switch arguments count and arguments offset += (argCount + 1) * 4; break; case OperandType.InlineI8: case OperandType.InlineR: offset += 8; break; case OperandType.InlineNone: break; case OperandType.InlineVar: offset += 2; break; case OperandType.ShortInlineBrTarget: case OperandType.ShortInlineI: case OperandType.ShortInlineVar: offset += 1; break; default: throw ExceptionUtilities.UnexpectedValue(operandType); } } } private void SerializeMethodBodyExceptionHandlerTable(ExceptionRegionEncoder encoder, ImmutableArray<ExceptionHandlerRegion> regions) { foreach (var region in regions) { var exceptionType = region.ExceptionType; encoder.Add( region.HandlerKind, region.TryStartOffset, region.TryLength, region.HandlerStartOffset, region.HandlerLength, (exceptionType != null) ? GetTypeHandle(exceptionType) : default(EntityHandle), region.FilterDecisionStartOffset); } } private static bool MayUseSmallExceptionHeaders(ImmutableArray<ExceptionHandlerRegion> exceptionRegions) { if (!ExceptionRegionEncoder.IsSmallRegionCount(exceptionRegions.Length)) { return false; } foreach (var region in exceptionRegions) { if (!ExceptionRegionEncoder.IsSmallExceptionRegion(region.TryStartOffset, region.TryLength) || !ExceptionRegionEncoder.IsSmallExceptionRegion(region.HandlerStartOffset, region.HandlerLength)) { return false; } } return true; } private void SerializeParameterInformation(ParameterTypeEncoder encoder, IParameterTypeInformation parameterTypeInformation) { var type = parameterTypeInformation.GetType(Context); if (module.IsPlatformType(type, PlatformType.SystemTypedReference)) { Debug.Assert(!parameterTypeInformation.IsByReference); SerializeCustomModifiers(encoder.CustomModifiers(), parameterTypeInformation.CustomModifiers); encoder.TypedReference(); } else { Debug.Assert(parameterTypeInformation.RefCustomModifiers.Length == 0 || parameterTypeInformation.IsByReference); SerializeCustomModifiers(encoder.CustomModifiers(), parameterTypeInformation.RefCustomModifiers); var typeEncoder = encoder.Type(parameterTypeInformation.IsByReference); SerializeCustomModifiers(typeEncoder.CustomModifiers(), parameterTypeInformation.CustomModifiers); SerializeTypeReference(typeEncoder, type); } } private void SerializeFieldSignature(IFieldReference fieldReference, BlobBuilder builder) { var typeEncoder = new BlobEncoder(builder).FieldSignature(); SerializeTypeReference(typeEncoder, fieldReference.GetType(Context)); } private void SerializeMethodSpecificationSignature(BlobBuilder builder, IGenericMethodInstanceReference genericMethodInstanceReference) { var argsEncoder = new BlobEncoder(builder).MethodSpecificationSignature(genericMethodInstanceReference.GetGenericMethod(Context).GenericParameterCount); foreach (ITypeReference genericArgument in genericMethodInstanceReference.GetGenericArguments(Context)) { ITypeReference typeRef = genericArgument; SerializeTypeReference(argsEncoder.AddArgument(), typeRef); } } private void SerializeCustomAttributeSignature(ICustomAttribute customAttribute, BlobBuilder builder) { var parameters = customAttribute.Constructor(Context, reportDiagnostics: false).GetParameters(Context); var arguments = customAttribute.GetArguments(Context); Debug.Assert(parameters.Length == arguments.Length); FixedArgumentsEncoder fixedArgsEncoder; CustomAttributeNamedArgumentsEncoder namedArgsEncoder; new BlobEncoder(builder).CustomAttributeSignature(out fixedArgsEncoder, out namedArgsEncoder); for (int i = 0; i < parameters.Length; i++) { SerializeMetadataExpression(fixedArgsEncoder.AddArgument(), arguments[i], parameters[i].GetType(Context)); } SerializeCustomAttributeNamedArguments(namedArgsEncoder.Count(customAttribute.NamedArgumentCount), customAttribute); } private void SerializeCustomAttributeNamedArguments(NamedArgumentsEncoder encoder, ICustomAttribute customAttribute) { foreach (IMetadataNamedArgument namedArgument in customAttribute.GetNamedArguments(Context)) { NamedArgumentTypeEncoder typeEncoder; NameEncoder nameEncoder; LiteralEncoder literalEncoder; encoder.AddArgument(namedArgument.IsField, out typeEncoder, out nameEncoder, out literalEncoder); SerializeNamedArgumentType(typeEncoder, namedArgument.Type); nameEncoder.Name(namedArgument.ArgumentName); SerializeMetadataExpression(literalEncoder, namedArgument.ArgumentValue, namedArgument.Type); } } private void SerializeNamedArgumentType(NamedArgumentTypeEncoder encoder, ITypeReference type) { if (type is IArrayTypeReference arrayType) { SerializeCustomAttributeArrayType(encoder.SZArray(), arrayType); } else if (module.IsPlatformType(type, PlatformType.SystemObject)) { encoder.Object(); } else { SerializeCustomAttributeElementType(encoder.ScalarType(), type); } } private void SerializeMetadataExpression(LiteralEncoder encoder, IMetadataExpression expression, ITypeReference targetType) { if (expression is MetadataCreateArray a) { ITypeReference targetElementType; VectorEncoder vectorEncoder; if (!(targetType is IArrayTypeReference targetArrayType)) { // implicit conversion from array to object Debug.Assert(this.module.IsPlatformType(targetType, PlatformType.SystemObject)); CustomAttributeArrayTypeEncoder arrayTypeEncoder; encoder.TaggedVector(out arrayTypeEncoder, out vectorEncoder); SerializeCustomAttributeArrayType(arrayTypeEncoder, a.ArrayType); targetElementType = a.ElementType; } else { vectorEncoder = encoder.Vector(); // In FixedArg the element type of the parameter array has to match the element type of the argument array, // but in NamedArg T[] can be assigned to object[]. In that case we need to encode the arguments using // the parameter element type not the argument element type. targetElementType = targetArrayType.GetElementType(this.Context); } var literalsEncoder = vectorEncoder.Count(a.Elements.Length); foreach (IMetadataExpression elemValue in a.Elements) { SerializeMetadataExpression(literalsEncoder.AddLiteral(), elemValue, targetElementType); } } else { ScalarEncoder scalarEncoder; MetadataConstant c = expression as MetadataConstant; if (this.module.IsPlatformType(targetType, PlatformType.SystemObject)) { CustomAttributeElementTypeEncoder typeEncoder; encoder.TaggedScalar(out typeEncoder, out scalarEncoder); // special case null argument assigned to Object parameter - treat as null string if (c != null && c.Value == null && this.module.IsPlatformType(c.Type, PlatformType.SystemObject)) { typeEncoder.String(); } else { SerializeCustomAttributeElementType(typeEncoder, expression.Type); } } else { scalarEncoder = encoder.Scalar(); } if (c != null) { if (c.Type is IArrayTypeReference) { scalarEncoder.NullArray(); return; } Debug.Assert(!module.IsPlatformType(c.Type, PlatformType.SystemType) || c.Value == null); scalarEncoder.Constant(c.Value); } else { scalarEncoder.SystemType(((MetadataTypeOf)expression).TypeToGet.GetSerializedTypeName(Context)); } } } private void SerializeMarshallingDescriptor(IMarshallingInformation marshallingInformation, BlobBuilder writer) { writer.WriteCompressedInteger((int)marshallingInformation.UnmanagedType); switch (marshallingInformation.UnmanagedType) { case UnmanagedType.ByValArray: // NATIVE_TYPE_FIXEDARRAY Debug.Assert(marshallingInformation.NumberOfElements >= 0); writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); if (marshallingInformation.ElementType >= 0) { writer.WriteCompressedInteger((int)marshallingInformation.ElementType); } break; case Constants.UnmanagedType_CustomMarshaler: writer.WriteUInt16(0); // padding object marshaller = marshallingInformation.GetCustomMarshaller(Context); switch (marshaller) { case ITypeReference marshallerTypeRef: this.SerializeTypeName(marshallerTypeRef, writer); break; case null: writer.WriteByte(0); break; default: writer.WriteSerializedString((string)marshaller); break; } var arg = marshallingInformation.CustomMarshallerRuntimeArgument; if (arg != null) { writer.WriteSerializedString(arg); } else { writer.WriteByte(0); } break; case UnmanagedType.LPArray: // NATIVE_TYPE_ARRAY Debug.Assert(marshallingInformation.ElementType >= 0); writer.WriteCompressedInteger((int)marshallingInformation.ElementType); if (marshallingInformation.ParamIndex >= 0) { writer.WriteCompressedInteger(marshallingInformation.ParamIndex); if (marshallingInformation.NumberOfElements >= 0) { writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); writer.WriteByte(1); // The parameter number is valid } } else if (marshallingInformation.NumberOfElements >= 0) { writer.WriteByte(0); // Dummy parameter value emitted so that NumberOfElements can be in a known position writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); writer.WriteByte(0); // The parameter number is not valid } break; case Constants.UnmanagedType_SafeArray: if (marshallingInformation.SafeArrayElementSubtype >= 0) { writer.WriteCompressedInteger((int)marshallingInformation.SafeArrayElementSubtype); var elementType = marshallingInformation.GetSafeArrayElementUserDefinedSubtype(Context); if (elementType != null) { this.SerializeTypeName(elementType, writer); } } break; case UnmanagedType.ByValTStr: // NATIVE_TYPE_FIXEDSYSSTRING writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); break; case UnmanagedType.Interface: case Constants.UnmanagedType_IDispatch: case UnmanagedType.IUnknown: if (marshallingInformation.IidParameterIndex >= 0) { writer.WriteCompressedInteger(marshallingInformation.IidParameterIndex); } break; } } private void SerializeTypeName(ITypeReference typeReference, BlobBuilder writer) { writer.WriteSerializedString(typeReference.GetSerializedTypeName(this.Context)); } /// <summary> /// Computes the string representing the strong name of the given assembly reference. /// </summary> internal static string StrongName(IAssemblyReference assemblyReference) { var identity = assemblyReference.Identity; var pooled = PooledStringBuilder.GetInstance(); StringBuilder sb = pooled.Builder; sb.Append(identity.Name); sb.AppendFormat(CultureInfo.InvariantCulture, ", Version={0}.{1}.{2}.{3}", identity.Version.Major, identity.Version.Minor, identity.Version.Build, identity.Version.Revision); if (!string.IsNullOrEmpty(identity.CultureName)) { sb.AppendFormat(CultureInfo.InvariantCulture, ", Culture={0}", identity.CultureName); } else { sb.Append(", Culture=neutral"); } sb.Append(", PublicKeyToken="); if (identity.PublicKeyToken.Length > 0) { foreach (byte b in identity.PublicKeyToken) { sb.Append(b.ToString("x2")); } } else { sb.Append("null"); } if (identity.IsRetargetable) { sb.Append(", Retargetable=Yes"); } if (identity.ContentType == AssemblyContentType.WindowsRuntime) { sb.Append(", ContentType=WindowsRuntime"); } else { Debug.Assert(identity.ContentType == AssemblyContentType.Default); } return pooled.ToStringAndFree(); } private void SerializePermissionSet(ImmutableArray<ICustomAttribute> permissionSet, BlobBuilder writer) { EmitContext context = this.Context; foreach (ICustomAttribute customAttribute in permissionSet) { bool isAssemblyQualified = true; string typeName = customAttribute.GetType(context).GetSerializedTypeName(context, ref isAssemblyQualified); if (!isAssemblyQualified) { INamespaceTypeReference namespaceType = customAttribute.GetType(context).AsNamespaceTypeReference; if (namespaceType?.GetUnit(context) is IAssemblyReference referencedAssembly) { typeName = typeName + ", " + StrongName(referencedAssembly); } } writer.WriteSerializedString(typeName); var customAttributeArgsBuilder = PooledBlobBuilder.GetInstance(); var namedArgsEncoder = new BlobEncoder(customAttributeArgsBuilder).PermissionSetArguments(customAttribute.NamedArgumentCount); SerializeCustomAttributeNamedArguments(namedArgsEncoder, customAttribute); writer.WriteCompressedInteger(customAttributeArgsBuilder.Count); customAttributeArgsBuilder.WriteContentTo(writer); customAttributeArgsBuilder.Free(); } // TODO: xml for older platforms } private void SerializeReturnValueAndParameters(MethodSignatureEncoder encoder, ISignature signature, ImmutableArray<IParameterTypeInformation> varargParameters) { var declaredParameters = signature.GetParameters(Context); var returnType = signature.GetType(Context); ReturnTypeEncoder returnTypeEncoder; ParametersEncoder parametersEncoder; encoder.Parameters(declaredParameters.Length + varargParameters.Length, out returnTypeEncoder, out parametersEncoder); if (module.IsPlatformType(returnType, PlatformType.SystemTypedReference)) { Debug.Assert(!signature.ReturnValueIsByRef); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); returnTypeEncoder.TypedReference(); } else if (module.IsPlatformType(returnType, PlatformType.SystemVoid)) { Debug.Assert(!signature.ReturnValueIsByRef); Debug.Assert(signature.RefCustomModifiers.IsEmpty); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); returnTypeEncoder.Void(); } else { Debug.Assert(signature.RefCustomModifiers.IsEmpty || signature.ReturnValueIsByRef); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.RefCustomModifiers); var typeEncoder = returnTypeEncoder.Type(signature.ReturnValueIsByRef); SerializeCustomModifiers(typeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); SerializeTypeReference(typeEncoder, returnType); } foreach (IParameterTypeInformation parameter in declaredParameters) { SerializeParameterInformation(parametersEncoder.AddParameter(), parameter); } if (varargParameters.Length > 0) { parametersEncoder = parametersEncoder.StartVarArgs(); foreach (IParameterTypeInformation parameter in varargParameters) { SerializeParameterInformation(parametersEncoder.AddParameter(), parameter); } } } private void SerializeTypeReference(SignatureTypeEncoder encoder, ITypeReference typeReference) { while (true) { // TYPEDREF is only allowed in RetType, Param, LocalVarSig signatures Debug.Assert(!module.IsPlatformType(typeReference, PlatformType.SystemTypedReference)); if (typeReference is IModifiedTypeReference modifiedTypeReference) { SerializeCustomModifiers(encoder.CustomModifiers(), modifiedTypeReference.CustomModifiers); typeReference = modifiedTypeReference.UnmodifiedType; continue; } var primitiveType = typeReference.TypeCode; switch (primitiveType) { case PrimitiveTypeCode.Pointer: case PrimitiveTypeCode.FunctionPointer: case PrimitiveTypeCode.NotPrimitive: break; default: SerializePrimitiveType(encoder, primitiveType); return; } if (typeReference is IPointerTypeReference pointerTypeReference) { typeReference = pointerTypeReference.GetTargetType(Context); encoder = encoder.Pointer(); continue; } if (typeReference is IFunctionPointerTypeReference functionPointerTypeReference) { var signature = functionPointerTypeReference.Signature; var signatureEncoder = encoder.FunctionPointer(convention: signature.CallingConvention.ToSignatureConvention()); SerializeReturnValueAndParameters(signatureEncoder, signature, varargParameters: ImmutableArray<IParameterTypeInformation>.Empty); return; } IGenericTypeParameterReference genericTypeParameterReference = typeReference.AsGenericTypeParameterReference; if (genericTypeParameterReference != null) { encoder.GenericTypeParameter( GetNumberOfInheritedTypeParameters(genericTypeParameterReference.DefiningType) + genericTypeParameterReference.Index); return; } if (typeReference is IArrayTypeReference arrayTypeReference) { typeReference = arrayTypeReference.GetElementType(Context); if (arrayTypeReference.IsSZArray) { encoder = encoder.SZArray(); continue; } else { SignatureTypeEncoder elementType; ArrayShapeEncoder arrayShape; encoder.Array(out elementType, out arrayShape); SerializeTypeReference(elementType, typeReference); arrayShape.Shape(arrayTypeReference.Rank, arrayTypeReference.Sizes, arrayTypeReference.LowerBounds); return; } } if (module.IsPlatformType(typeReference, PlatformType.SystemObject)) { encoder.Object(); return; } IGenericMethodParameterReference genericMethodParameterReference = typeReference.AsGenericMethodParameterReference; if (genericMethodParameterReference != null) { encoder.GenericMethodTypeParameter(genericMethodParameterReference.Index); return; } if (typeReference.IsTypeSpecification()) { ITypeReference uninstantiatedTypeReference = typeReference.GetUninstantiatedGenericType(Context); // Roslyn's uninstantiated type is the same object as the instantiated type for // types closed over their type parameters, so to speak. var consolidatedTypeArguments = ArrayBuilder<ITypeReference>.GetInstance(); typeReference.GetConsolidatedTypeArguments(consolidatedTypeArguments, this.Context); var genericArgsEncoder = encoder.GenericInstantiation( GetTypeHandle(uninstantiatedTypeReference, treatRefAsPotentialTypeSpec: false), consolidatedTypeArguments.Count, typeReference.IsValueType); foreach (ITypeReference typeArgument in consolidatedTypeArguments) { SerializeTypeReference(genericArgsEncoder.AddArgument(), typeArgument); } consolidatedTypeArguments.Free(); return; } encoder.Type(GetTypeHandle(typeReference), typeReference.IsValueType); return; } } private static void SerializePrimitiveType(SignatureTypeEncoder encoder, PrimitiveTypeCode primitiveType) { switch (primitiveType) { case PrimitiveTypeCode.Boolean: encoder.Boolean(); break; case PrimitiveTypeCode.UInt8: encoder.Byte(); break; case PrimitiveTypeCode.Int8: encoder.SByte(); break; case PrimitiveTypeCode.Char: encoder.Char(); break; case PrimitiveTypeCode.Int16: encoder.Int16(); break; case PrimitiveTypeCode.UInt16: encoder.UInt16(); break; case PrimitiveTypeCode.Int32: encoder.Int32(); break; case PrimitiveTypeCode.UInt32: encoder.UInt32(); break; case PrimitiveTypeCode.Int64: encoder.Int64(); break; case PrimitiveTypeCode.UInt64: encoder.UInt64(); break; case PrimitiveTypeCode.Float32: encoder.Single(); break; case PrimitiveTypeCode.Float64: encoder.Double(); break; case PrimitiveTypeCode.IntPtr: encoder.IntPtr(); break; case PrimitiveTypeCode.UIntPtr: encoder.UIntPtr(); break; case PrimitiveTypeCode.String: encoder.String(); break; case PrimitiveTypeCode.Void: // "void" is handled specifically for "void*" with custom modifiers. // If SignatureTypeEncoder supports such cases directly, this can // be removed. See https://github.com/dotnet/corefx/issues/14571. encoder.Builder.WriteByte((byte)System.Reflection.Metadata.PrimitiveTypeCode.Void); break; default: throw ExceptionUtilities.UnexpectedValue(primitiveType); } } private void SerializeCustomAttributeArrayType(CustomAttributeArrayTypeEncoder encoder, IArrayTypeReference arrayTypeReference) { // A single-dimensional, zero-based array is specified as a single byte 0x1D followed by the FieldOrPropType of the element type. // only non-jagged SZ arrays are allowed in attributes // (need to encode the type of the SZ array if the parameter type is Object): Debug.Assert(arrayTypeReference.IsSZArray); var elementType = arrayTypeReference.GetElementType(Context); Debug.Assert(!(elementType is IModifiedTypeReference)); if (module.IsPlatformType(elementType, PlatformType.SystemObject)) { encoder.ObjectArray(); } else { SerializeCustomAttributeElementType(encoder.ElementType(), elementType); } } private void SerializeCustomAttributeElementType(CustomAttributeElementTypeEncoder encoder, ITypeReference typeReference) { // Spec: // The FieldOrPropType shall be exactly one of: // ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_I1, ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_U2, ELEMENT_TYPE_I4, // ELEMENT_TYPE_U4, ELEMENT_TYPE_I8, ELEMENT_TYPE_U8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, ELEMENT_TYPE_STRING. // An enum is specified as a single byte 0x55 followed by a SerString. var primitiveType = typeReference.TypeCode; if (primitiveType != PrimitiveTypeCode.NotPrimitive) { SerializePrimitiveType(encoder, primitiveType); } else if (module.IsPlatformType(typeReference, PlatformType.SystemType)) { encoder.SystemType(); } else { Debug.Assert(typeReference.IsEnum); encoder.Enum(typeReference.GetSerializedTypeName(this.Context)); } } private static void SerializePrimitiveType(CustomAttributeElementTypeEncoder encoder, PrimitiveTypeCode primitiveType) { switch (primitiveType) { case PrimitiveTypeCode.Boolean: encoder.Boolean(); break; case PrimitiveTypeCode.UInt8: encoder.Byte(); break; case PrimitiveTypeCode.Int8: encoder.SByte(); break; case PrimitiveTypeCode.Char: encoder.Char(); break; case PrimitiveTypeCode.Int16: encoder.Int16(); break; case PrimitiveTypeCode.UInt16: encoder.UInt16(); break; case PrimitiveTypeCode.Int32: encoder.Int32(); break; case PrimitiveTypeCode.UInt32: encoder.UInt32(); break; case PrimitiveTypeCode.Int64: encoder.Int64(); break; case PrimitiveTypeCode.UInt64: encoder.UInt64(); break; case PrimitiveTypeCode.Float32: encoder.Single(); break; case PrimitiveTypeCode.Float64: encoder.Double(); break; case PrimitiveTypeCode.String: encoder.String(); break; default: throw ExceptionUtilities.UnexpectedValue(primitiveType); } } private void SerializeCustomModifiers(CustomModifiersEncoder encoder, ImmutableArray<ICustomModifier> modifiers) { foreach (var modifier in modifiers) { encoder = encoder.AddModifier(GetTypeHandle(modifier.GetModifier(Context)), modifier.IsOptional); } } private int GetNumberOfInheritedTypeParameters(ITypeReference type) { INestedTypeReference nestedType = type.AsNestedTypeReference; if (nestedType == null) { return 0; } ISpecializedNestedTypeReference specializedNestedType = nestedType.AsSpecializedNestedTypeReference; if (specializedNestedType != null) { nestedType = specializedNestedType.GetUnspecializedVersion(Context); } int result = 0; type = nestedType.GetContainingType(Context); nestedType = type.AsNestedTypeReference; while (nestedType != null) { result += nestedType.GenericParameterCount; type = nestedType.GetContainingType(Context); nestedType = type.AsNestedTypeReference; } result += type.AsNamespaceTypeReference.GenericParameterCount; return result; } internal static EditAndContinueMethodDebugInformation GetEncMethodDebugInfo(IMethodBody methodBody) { ImmutableArray<LocalSlotDebugInfo> encLocalSlots; // Kickoff method of a state machine (async/iterator method) doesn't have any interesting locals, // so we use its EnC method debug info to store information about locals hoisted to the state machine. var encSlotInfo = methodBody.StateMachineHoistedLocalSlots; if (encSlotInfo.IsDefault) { encLocalSlots = GetLocalSlotDebugInfos(methodBody.LocalVariables); } else { encLocalSlots = GetLocalSlotDebugInfos(encSlotInfo); } return new EditAndContinueMethodDebugInformation(methodBody.MethodId.Ordinal, encLocalSlots, methodBody.ClosureDebugInfo, methodBody.LambdaDebugInfo); } internal static ImmutableArray<LocalSlotDebugInfo> GetLocalSlotDebugInfos(ImmutableArray<ILocalDefinition> locals) { if (!locals.Any(variable => !variable.SlotInfo.Id.IsNone)) { return ImmutableArray<LocalSlotDebugInfo>.Empty; } return locals.SelectAsArray(variable => variable.SlotInfo); } internal static ImmutableArray<LocalSlotDebugInfo> GetLocalSlotDebugInfos(ImmutableArray<EncHoistedLocalInfo> locals) { if (!locals.Any(variable => !variable.SlotInfo.Id.IsNone)) { return ImmutableArray<LocalSlotDebugInfo>.Empty; } return locals.SelectAsArray(variable => variable.SlotInfo); } protected abstract class HeapOrReferenceIndexBase<T> { private readonly MetadataWriter _writer; private readonly List<T> _rows; private readonly int _firstRowId; protected HeapOrReferenceIndexBase(MetadataWriter writer, int lastRowId) { _writer = writer; _rows = new List<T>(); _firstRowId = lastRowId + 1; } public abstract bool TryGetValue(T item, out int index); public int GetOrAdd(T item) { int index; if (!this.TryGetValue(item, out index)) { index = Add(item); } return index; } public IReadOnlyList<T> Rows { get { return _rows; } } public int Add(T item) { Debug.Assert(!_writer._tableIndicesAreComplete); #if DEBUG int i; Debug.Assert(!this.TryGetValue(item, out i)); #endif int index = _firstRowId + _rows.Count; this.AddItem(item, index); _rows.Add(item); return index; } protected abstract void AddItem(T item, int index); } protected sealed class HeapOrReferenceIndex<T> : HeapOrReferenceIndexBase<T> { private readonly Dictionary<T, int> _index; public HeapOrReferenceIndex(MetadataWriter writer, int lastRowId = 0) : this(writer, new Dictionary<T, int>(), lastRowId) { } private HeapOrReferenceIndex(MetadataWriter writer, Dictionary<T, int> index, int lastRowId) : base(writer, lastRowId) { Debug.Assert(index.Count == 0); _index = index; } public override bool TryGetValue(T item, out int index) { return _index.TryGetValue(item, out index); } protected override void AddItem(T item, int index) { _index.Add(item, index); } } protected sealed class TypeReferenceIndex : HeapOrReferenceIndexBase<ITypeReference> { private readonly Dictionary<ITypeReference, int> _index; public TypeReferenceIndex(MetadataWriter writer, int lastRowId = 0) : this(writer, new Dictionary<ITypeReference, int>(ReferenceEqualityComparer.Instance), lastRowId) { } private TypeReferenceIndex(MetadataWriter writer, Dictionary<ITypeReference, int> index, int lastRowId) : base(writer, lastRowId) { Debug.Assert(index.Count == 0); _index = index; } public override bool TryGetValue(ITypeReference item, out int index) { return _index.TryGetValue(item, out index); } protected override void AddItem(ITypeReference item, int index) { _index.Add(item, index); } } protected sealed class InstanceAndStructuralReferenceIndex<T> : HeapOrReferenceIndexBase<T> where T : class, IReference { private readonly Dictionary<T, int> _instanceIndex; private readonly Dictionary<T, int> _structuralIndex; public InstanceAndStructuralReferenceIndex(MetadataWriter writer, IEqualityComparer<T> structuralComparer, int lastRowId = 0) : base(writer, lastRowId) { _instanceIndex = new Dictionary<T, int>(ReferenceEqualityComparer.Instance); _structuralIndex = new Dictionary<T, int>(structuralComparer); } public override bool TryGetValue(T item, out int index) { if (_instanceIndex.TryGetValue(item, out index)) { return true; } if (_structuralIndex.TryGetValue(item, out index)) { _instanceIndex.Add(item, index); return true; } return false; } protected override void AddItem(T item, int index) { _instanceIndex.Add(item, index); _structuralIndex.Add(item, index); } } private class ByteSequenceBoolTupleComparer : IEqualityComparer<(ImmutableArray<byte>, bool)> { internal static readonly ByteSequenceBoolTupleComparer Instance = new ByteSequenceBoolTupleComparer(); private ByteSequenceBoolTupleComparer() { } bool IEqualityComparer<(ImmutableArray<byte>, bool)>.Equals((ImmutableArray<byte>, bool) x, (ImmutableArray<byte>, bool) y) { return x.Item2 == y.Item2 && ByteSequenceComparer.Equals(x.Item1, y.Item1); } int IEqualityComparer<(ImmutableArray<byte>, bool)>.GetHashCode((ImmutableArray<byte>, bool) x) { return Hash.Combine(ByteSequenceComparer.GetHashCode(x.Item1), x.Item2.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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.Cci { internal abstract partial class MetadataWriter { internal static readonly Encoding s_utf8Encoding = Encoding.UTF8; /// <summary> /// This is the maximum length of a type or member name in metadata, assuming /// the name is in UTF-8 format and not (yet) null-terminated. /// </summary> /// <remarks> /// Source names may have to be shorter still to accommodate mangling. /// Used for event names, field names, property names, field names, method def names, /// member ref names, type def (full) names, type ref (full) names, exported type /// (full) names, parameter names, manifest resource names, and unmanaged method names /// (ImplMap table). /// /// See CLI Part II, section 22. /// </remarks> internal const int NameLengthLimit = 1024 - 1; //MAX_CLASS_NAME = 1024 in dev11 /// <summary> /// This is the maximum length of a path in metadata, assuming the path is in UTF-8 /// format and not (yet) null-terminated. /// </summary> /// <remarks> /// Used for file names, module names, and module ref names. /// /// See CLI Part II, section 22. /// </remarks> internal const int PathLengthLimit = 260 - 1; //MAX_PATH = 1024 in dev11 /// <summary> /// This is the maximum length of a string in the PDB, assuming it is in UTF-8 format /// and not (yet) null-terminated. /// </summary> /// <remarks> /// Used for import strings, locals, and local constants. /// </remarks> internal const int PdbLengthLimit = 2046; // Empirical, based on when ISymUnmanagedWriter2 methods start throwing. private readonly int _numTypeDefsEstimate; private readonly bool _deterministic; internal readonly bool MetadataOnly; internal readonly bool EmitTestCoverageData; // A map of method body before token translation to RVA. Used for deduplication of small bodies. private readonly Dictionary<(ImmutableArray<byte>, bool), int> _smallMethodBodies; private const byte TinyFormat = 2; private const int ThrowNullCodeSize = 2; private static readonly ImmutableArray<byte> ThrowNullEncodedBody = ImmutableArray.Create( (byte)((ThrowNullCodeSize << 2) | TinyFormat), (byte)ILOpCode.Ldnull, (byte)ILOpCode.Throw); protected MetadataWriter( MetadataBuilder metadata, MetadataBuilder debugMetadataOpt, DynamicAnalysisDataWriter dynamicAnalysisDataWriterOpt, EmitContext context, CommonMessageProvider messageProvider, bool metadataOnly, bool deterministic, bool emitTestCoverageData, CancellationToken cancellationToken) { Debug.Assert(metadata != debugMetadataOpt); this.module = context.Module; _deterministic = deterministic; this.MetadataOnly = metadataOnly; this.EmitTestCoverageData = emitTestCoverageData; // EDMAURER provide some reasonable size estimates for these that will avoid // much of the reallocation that would occur when growing these from empty. _signatureIndex = new Dictionary<ISignature, KeyValuePair<BlobHandle, ImmutableArray<byte>>>(module.HintNumberOfMethodDefinitions, ReferenceEqualityComparer.Instance); //ignores field signatures _numTypeDefsEstimate = module.HintNumberOfMethodDefinitions / 6; this.Context = context; this.messageProvider = messageProvider; _cancellationToken = cancellationToken; this.metadata = metadata; _debugMetadataOpt = debugMetadataOpt; _dynamicAnalysisDataWriterOpt = dynamicAnalysisDataWriterOpt; _smallMethodBodies = new Dictionary<(ImmutableArray<byte>, bool), int>(ByteSequenceBoolTupleComparer.Instance); } private int NumberOfTypeDefsEstimate { get { return _numTypeDefsEstimate; } } /// <summary> /// Returns true if writing full metadata, false if writing delta. /// </summary> internal bool IsFullMetadata { get { return this.Generation == 0; } } /// <summary> /// True if writing delta metadata in a minimal format. /// </summary> private bool IsMinimalDelta { get { return !IsFullMetadata; } } /// <summary> /// NetModules and EnC deltas don't have AssemblyDef record. /// We don't emit it for EnC deltas since assembly identity has to be preserved across generations (CLR/debugger get confused otherwise). /// </summary> private bool EmitAssemblyDefinition => module.OutputKind != OutputKind.NetModule && !IsMinimalDelta; /// <summary> /// Returns metadata generation ordinal. Zero for /// full metadata and non-zero for delta. /// </summary> protected abstract ushort Generation { get; } /// <summary> /// Returns unique Guid for this delta, or default(Guid) /// if full metadata. /// </summary> protected abstract Guid EncId { get; } /// <summary> /// Returns Guid of previous delta, or default(Guid) /// if full metadata or generation 1 delta. /// </summary> protected abstract Guid EncBaseId { get; } /// <summary> /// Returns true and full metadata handle of the type definition /// if the type definition is recognized. Otherwise returns false. /// </summary> protected abstract bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle); /// <summary> /// Get full metadata handle of the type definition. /// </summary> protected abstract TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def); /// <summary> /// The type definition corresponding to full metadata type handle. /// Deltas are only required to support indexing into current generation. /// </summary> protected abstract ITypeDefinition GetTypeDef(TypeDefinitionHandle handle); /// <summary> /// The type definitions to be emitted, in row order. These /// are just the type definitions from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeDefinition> GetTypeDefs(); /// <summary> /// Get full metadata handle of the event definition. /// </summary> protected abstract EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def); /// <summary> /// The event definitions to be emitted, in row order. These /// are just the event definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IEventDefinition> GetEventDefs(); /// <summary> /// Get full metadata handle of the field definition. /// </summary> protected abstract FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def); /// <summary> /// The field definitions to be emitted, in row order. These /// are just the field definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IFieldDefinition> GetFieldDefs(); /// <summary> /// Returns true and handle of the method definition /// if the method definition is recognized. Otherwise returns false. /// The index is into the full metadata. /// </summary> protected abstract bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle); /// <summary> /// Get full metadata handle of the method definition. /// </summary> protected abstract MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def); /// <summary> /// The method definition corresponding to full metadata method handle. /// Deltas are only required to support indexing into current generation. /// </summary> protected abstract IMethodDefinition GetMethodDef(MethodDefinitionHandle handle); /// <summary> /// The method definitions to be emitted, in row order. These /// are just the method definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IMethodDefinition> GetMethodDefs(); /// <summary> /// Get full metadata handle of the property definition. /// </summary> protected abstract PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def); /// <summary> /// The property definitions to be emitted, in row order. These /// are just the property definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IPropertyDefinition> GetPropertyDefs(); /// <summary> /// The full metadata handle of the parameter definition. /// </summary> protected abstract ParameterHandle GetParameterHandle(IParameterDefinition def); /// <summary> /// The parameter definitions to be emitted, in row order. These /// are just the parameter definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IParameterDefinition> GetParameterDefs(); /// <summary> /// The generic parameter definitions to be emitted, in row order. These /// are just the generic parameter definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IGenericParameter> GetGenericParameters(); /// <summary> /// The handle of the first field of the type. /// </summary> protected abstract FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef); /// <summary> /// The handle of the first method of the type. /// </summary> protected abstract MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef); /// <summary> /// The handle of the first parameter of the method. /// </summary> protected abstract ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef); /// <summary> /// Return full metadata handle of the assembly reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference); /// <summary> /// The assembly references to be emitted, in row order. These /// are just the assembly references from the current generation. /// </summary> protected abstract IReadOnlyList<AssemblyIdentity> GetAssemblyRefs(); // ModuleRef table contains module names for TypeRefs that target types in netmodules (represented by IModuleReference), // and module names specified by P/Invokes (plain strings). Names in the table must be unique and are case sensitive. // // Spec 22.31 (ModuleRef : 0x1A) // "Name should match an entry in the Name column of the File table. Moreover, that entry shall enable the // CLI to locate the target module (typically it might name the file used to hold the module)" // // This is not how the Dev10 compilers and ILASM work. An entry is added to File table only for resources and netmodules. // Entries aren't added for P/Invoked modules. /// <summary> /// Return full metadata handle of the module reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference); /// <summary> /// The module references to be emitted, in row order. These /// are just the module references from the current generation. /// </summary> protected abstract IReadOnlyList<string> GetModuleRefs(); /// <summary> /// Return full metadata handle of the member reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference); /// <summary> /// The member references to be emitted, in row order. These /// are just the member references from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeMemberReference> GetMemberRefs(); /// <summary> /// Return full metadata handle of the method spec, adding /// the spec to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference); /// <summary> /// The method specs to be emitted, in row order. These /// are just the method specs from the current generation. /// </summary> protected abstract IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs(); /// <summary> /// The greatest index given to any method definition. /// </summary> protected abstract int GreatestMethodDefIndex { get; } /// <summary> /// Return true and full metadata handle of the type reference /// if the reference is available in the current generation. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle); /// <summary> /// Return full metadata handle of the type reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference); /// <summary> /// The type references to be emitted, in row order. These /// are just the type references from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeReference> GetTypeRefs(); /// <summary> /// Returns full metadata handle of the type spec, adding /// the spec to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference); /// <summary> /// The type specs to be emitted, in row order. These /// are just the type specs from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeReference> GetTypeSpecs(); /// <summary> /// Returns full metadata handle the standalone signature, adding /// the signature to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle handle); /// <summary> /// The signature blob handles to be emitted, in row order. These /// are just the signature indices from the current generation. /// </summary> protected abstract IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles(); protected abstract void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef); /// <summary> /// Return a visitor for traversing all references to be emitted. /// </summary> protected abstract ReferenceIndexer CreateReferenceVisitor(); /// <summary> /// Populate EventMap table. /// </summary> protected abstract void PopulateEventMapTableRows(); /// <summary> /// Populate PropertyMap table. /// </summary> protected abstract void PopulatePropertyMapTableRows(); protected abstract void ReportReferencesToAddedSymbols(); // If true, it is allowed to have methods not have bodies (for emitting metadata-only // assembly) private readonly CancellationToken _cancellationToken; protected readonly CommonPEModuleBuilder module; public readonly EmitContext Context; protected readonly CommonMessageProvider messageProvider; // progress: private bool _tableIndicesAreComplete; private bool _usingNonSourceDocumentNameEnumerator; private ImmutableArray<string>.Enumerator _nonSourceDocumentNameEnumerator; private EntityHandle[] _pseudoSymbolTokenToTokenMap; private object[] _pseudoSymbolTokenToReferenceMap; private UserStringHandle[] _pseudoStringTokenToTokenMap; private bool _userStringTokenOverflow; private List<string> _pseudoStringTokenToStringMap; private ReferenceIndexer _referenceVisitor; protected readonly MetadataBuilder metadata; // A builder for Portable or Embedded PDB metadata, or null if we are not emitting Portable/Embedded PDB. protected readonly MetadataBuilder _debugMetadataOpt; internal bool EmitPortableDebugMetadata => _debugMetadataOpt != null; private readonly DynamicAnalysisDataWriter _dynamicAnalysisDataWriterOpt; private readonly Dictionary<ICustomAttribute, BlobHandle> _customAttributeSignatureIndex = new Dictionary<ICustomAttribute, BlobHandle>(); private readonly Dictionary<ITypeReference, BlobHandle> _typeSpecSignatureIndex = new Dictionary<ITypeReference, BlobHandle>(ReferenceEqualityComparer.Instance); private readonly Dictionary<string, int> _fileRefIndex = new Dictionary<string, int>(32); // more than enough in most cases, value is a RowId private readonly List<IFileReference> _fileRefList = new List<IFileReference>(32); private readonly Dictionary<IFieldReference, BlobHandle> _fieldSignatureIndex = new Dictionary<IFieldReference, BlobHandle>(ReferenceEqualityComparer.Instance); // We need to keep track of both the index of the signature and the actual blob to support VB static local naming scheme. private readonly Dictionary<ISignature, KeyValuePair<BlobHandle, ImmutableArray<byte>>> _signatureIndex; private readonly Dictionary<IMarshallingInformation, BlobHandle> _marshallingDescriptorIndex = new Dictionary<IMarshallingInformation, BlobHandle>(); protected readonly List<MethodImplementation> methodImplList = new List<MethodImplementation>(); private readonly Dictionary<IGenericMethodInstanceReference, BlobHandle> _methodInstanceSignatureIndex = new Dictionary<IGenericMethodInstanceReference, BlobHandle>(ReferenceEqualityComparer.Instance); // Well known dummy cor library types whose refs are used for attaching assembly attributes off within net modules // There is no guarantee the types actually exist in a cor library internal const string dummyAssemblyAttributeParentNamespace = "System.Runtime.CompilerServices"; internal const string dummyAssemblyAttributeParentName = "AssemblyAttributesGoHere"; internal static readonly string[,] dummyAssemblyAttributeParentQualifier = { { "", "M" }, { "S", "SM" } }; private readonly TypeReferenceHandle[,] _dummyAssemblyAttributeParent = { { default(TypeReferenceHandle), default(TypeReferenceHandle) }, { default(TypeReferenceHandle), default(TypeReferenceHandle) } }; internal CommonPEModuleBuilder Module => module; private void CreateMethodBodyReferenceIndex() { var referencesInIL = module.ReferencesInIL(); _pseudoSymbolTokenToTokenMap = new EntityHandle[referencesInIL.Length]; _pseudoSymbolTokenToReferenceMap = referencesInIL.ToArray(); } private void CreateIndices() { _cancellationToken.ThrowIfCancellationRequested(); this.CreateUserStringIndices(); this.CreateInitialAssemblyRefIndex(); this.CreateInitialFileRefIndex(); this.CreateIndicesForModule(); // Find all references and assign tokens. _referenceVisitor = this.CreateReferenceVisitor(); _referenceVisitor.Visit(module); this.CreateMethodBodyReferenceIndex(); this.OnIndicesCreated(); } private void CreateUserStringIndices() { _pseudoStringTokenToStringMap = new List<string>(); foreach (string str in this.module.GetStrings()) { _pseudoStringTokenToStringMap.Add(str); } _pseudoStringTokenToTokenMap = new UserStringHandle[_pseudoStringTokenToStringMap.Count]; } private void CreateIndicesForModule() { var nestedTypes = new Queue<INestedTypeDefinition>(); foreach (INamespaceTypeDefinition typeDef in module.GetTopLevelTypeDefinitions(Context)) { this.CreateIndicesFor(typeDef, nestedTypes); } while (nestedTypes.Count > 0) { var nestedType = nestedTypes.Dequeue(); this.CreateIndicesFor(nestedType, nestedTypes); } } protected virtual void OnIndicesCreated() { } private void CreateIndicesFor(ITypeDefinition typeDef, Queue<INestedTypeDefinition> nestedTypes) { _cancellationToken.ThrowIfCancellationRequested(); this.CreateIndicesForNonTypeMembers(typeDef); // Metadata spec: // The TypeDef table has a special ordering constraint: // the definition of an enclosing class shall precede the definition of all classes it encloses. foreach (var nestedType in typeDef.GetNestedTypes(Context)) { nestedTypes.Enqueue(nestedType); } } protected IEnumerable<IGenericTypeParameter> GetConsolidatedTypeParameters(ITypeDefinition typeDef) { INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef == null) { if (typeDef.IsGeneric) { return typeDef.GenericParameters; } return null; } return this.GetConsolidatedTypeParameters(typeDef, typeDef); } private List<IGenericTypeParameter> GetConsolidatedTypeParameters(ITypeDefinition typeDef, ITypeDefinition owner) { List<IGenericTypeParameter> result = null; INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef != null) { result = this.GetConsolidatedTypeParameters(nestedTypeDef.ContainingTypeDefinition, owner); } if (typeDef.GenericParameterCount > 0) { ushort index = 0; if (result == null) { result = new List<IGenericTypeParameter>(); } else { index = (ushort)result.Count; } if (typeDef == owner && index == 0) { result.AddRange(typeDef.GenericParameters); } else { foreach (IGenericTypeParameter genericParameter in typeDef.GenericParameters) { result.Add(new InheritedTypeParameter(index++, owner, genericParameter)); } } } return result; } protected ImmutableArray<IParameterDefinition> GetParametersToEmit(IMethodDefinition methodDef) { if (methodDef.ParameterCount == 0 && !(methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context)))) { return ImmutableArray<IParameterDefinition>.Empty; } return GetParametersToEmitCore(methodDef); } private ImmutableArray<IParameterDefinition> GetParametersToEmitCore(IMethodDefinition methodDef) { ArrayBuilder<IParameterDefinition> builder = null; var parameters = methodDef.Parameters; if (methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context))) { builder = ArrayBuilder<IParameterDefinition>.GetInstance(parameters.Length + 1); builder.Add(new ReturnValueParameter(methodDef)); } for (int i = 0; i < parameters.Length; i++) { IParameterDefinition parDef = parameters[i]; // No explicit param row is needed if param has no flags (other than optionally IN), // no name and no references to the param row, such as CustomAttribute, Constant, or FieldMarshal if (parDef.Name != String.Empty || parDef.HasDefaultValue || parDef.IsOptional || parDef.IsOut || parDef.IsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(parDef.GetAttributes(Context))) { if (builder != null) { builder.Add(parDef); } } else { // we have a parameter that does not need to be emitted (not common) if (builder == null) { builder = ArrayBuilder<IParameterDefinition>.GetInstance(parameters.Length); builder.AddRange(parameters, i); } } } return builder?.ToImmutableAndFree() ?? parameters; } /// <summary> /// Returns a reference to the unit that defines the given referenced type. If the referenced type is a structural type, such as a pointer or a generic type instance, /// then the result is null. /// </summary> public static IUnitReference GetDefiningUnitReference(ITypeReference typeReference, EmitContext context) { INestedTypeReference nestedTypeReference = typeReference.AsNestedTypeReference; while (nestedTypeReference != null) { if (nestedTypeReference.AsGenericTypeInstanceReference != null) { return null; } typeReference = nestedTypeReference.GetContainingType(context); nestedTypeReference = typeReference.AsNestedTypeReference; } INamespaceTypeReference namespaceTypeReference = typeReference.AsNamespaceTypeReference; if (namespaceTypeReference == null) { return null; } Debug.Assert(namespaceTypeReference.AsGenericTypeInstanceReference == null); return namespaceTypeReference.GetUnit(context); } private void CreateInitialAssemblyRefIndex() { Debug.Assert(!_tableIndicesAreComplete); foreach (IAssemblyReference assemblyRef in this.module.GetAssemblyReferences(Context)) { this.GetOrAddAssemblyReferenceHandle(assemblyRef); } } private void CreateInitialFileRefIndex() { Debug.Assert(!_tableIndicesAreComplete); foreach (IFileReference fileRef in module.GetFiles(Context)) { string key = fileRef.FileName; if (!_fileRefIndex.ContainsKey(key)) { _fileRefList.Add(fileRef); _fileRefIndex.Add(key, _fileRefList.Count); } } } internal AssemblyReferenceHandle GetAssemblyReferenceHandle(IAssemblyReference assemblyReference) { var containingAssembly = this.module.GetContainingAssembly(Context); if (containingAssembly != null && ReferenceEquals(assemblyReference, containingAssembly)) { return default(AssemblyReferenceHandle); } return this.GetOrAddAssemblyReferenceHandle(assemblyReference); } internal ModuleReferenceHandle GetModuleReferenceHandle(string moduleName) { return this.GetOrAddModuleReferenceHandle(moduleName); } private BlobHandle GetCustomAttributeSignatureIndex(ICustomAttribute customAttribute) { BlobHandle result; if (_customAttributeSignatureIndex.TryGetValue(customAttribute, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeCustomAttributeSignature(customAttribute, writer); result = metadata.GetOrAddBlob(writer); _customAttributeSignatureIndex.Add(customAttribute, result); writer.Free(); return result; } private EntityHandle GetCustomAttributeTypeCodedIndex(IMethodReference methodReference) { IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } return methodDef != null ? (EntityHandle)GetMethodDefinitionHandle(methodDef) : GetMemberReferenceHandle(methodReference); } public static EventAttributes GetEventAttributes(IEventDefinition eventDef) { EventAttributes result = 0; if (eventDef.IsSpecialName) { result |= EventAttributes.SpecialName; } if (eventDef.IsRuntimeSpecial) { result |= EventAttributes.RTSpecialName; } return result; } public static FieldAttributes GetFieldAttributes(IFieldDefinition fieldDef) { var result = (FieldAttributes)fieldDef.Visibility; if (fieldDef.IsStatic) { result |= FieldAttributes.Static; } if (fieldDef.IsReadOnly) { result |= FieldAttributes.InitOnly; } if (fieldDef.IsCompileTimeConstant) { result |= FieldAttributes.Literal; } if (fieldDef.IsNotSerialized) { result |= FieldAttributes.NotSerialized; } if (!fieldDef.MappedData.IsDefault) { result |= FieldAttributes.HasFieldRVA; } if (fieldDef.IsSpecialName) { result |= FieldAttributes.SpecialName; } if (fieldDef.IsRuntimeSpecial) { result |= FieldAttributes.RTSpecialName; } if (fieldDef.IsMarshalledExplicitly) { result |= FieldAttributes.HasFieldMarshal; } if (fieldDef.IsCompileTimeConstant) { result |= FieldAttributes.HasDefault; } return result; } internal BlobHandle GetFieldSignatureIndex(IFieldReference fieldReference) { BlobHandle result; ISpecializedFieldReference specializedFieldReference = fieldReference.AsSpecializedFieldReference; if (specializedFieldReference != null) { fieldReference = specializedFieldReference.UnspecializedVersion; } if (_fieldSignatureIndex.TryGetValue(fieldReference, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeFieldSignature(fieldReference, writer); result = metadata.GetOrAddBlob(writer); _fieldSignatureIndex.Add(fieldReference, result); writer.Free(); return result; } internal EntityHandle GetFieldHandle(IFieldReference fieldReference) { IFieldDefinition fieldDef = null; IUnitReference definingUnit = GetDefiningUnitReference(fieldReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { fieldDef = fieldReference.GetResolvedField(Context); } return fieldDef != null ? (EntityHandle)GetFieldDefinitionHandle(fieldDef) : GetMemberReferenceHandle(fieldReference); } internal AssemblyFileHandle GetAssemblyFileHandle(IFileReference fileReference) { string key = fileReference.FileName; int index; if (!_fileRefIndex.TryGetValue(key, out index)) { Debug.Assert(!_tableIndicesAreComplete); _fileRefList.Add(fileReference); _fileRefIndex.Add(key, index = _fileRefList.Count); } return MetadataTokens.AssemblyFileHandle(index); } private AssemblyFileHandle GetAssemblyFileHandle(IModuleReference mref) { return MetadataTokens.AssemblyFileHandle(_fileRefIndex[mref.Name]); } private static GenericParameterAttributes GetGenericParameterAttributes(IGenericParameter genPar) { GenericParameterAttributes result = 0; switch (genPar.Variance) { case TypeParameterVariance.Covariant: result |= GenericParameterAttributes.Covariant; break; case TypeParameterVariance.Contravariant: result |= GenericParameterAttributes.Contravariant; break; } if (genPar.MustBeReferenceType) { result |= GenericParameterAttributes.ReferenceTypeConstraint; } if (genPar.MustBeValueType) { result |= GenericParameterAttributes.NotNullableValueTypeConstraint; } if (genPar.MustHaveDefaultConstructor) { result |= GenericParameterAttributes.DefaultConstructorConstraint; } return result; } private EntityHandle GetExportedTypeImplementation(INamespaceTypeReference namespaceRef) { IUnitReference uref = namespaceRef.GetUnit(Context); if (uref is IAssemblyReference aref) { return GetAssemblyReferenceHandle(aref); } var mref = (IModuleReference)uref; aref = mref.GetContainingAssembly(Context); return aref == null || ReferenceEquals(aref, this.module.GetContainingAssembly(Context)) ? (EntityHandle)GetAssemblyFileHandle(mref) : GetAssemblyReferenceHandle(aref); } private static uint GetManagedResourceOffset(ManagedResource resource, BlobBuilder resourceWriter) { if (resource.ExternalFile != null) { return resource.Offset; } int result = resourceWriter.Count; resource.WriteData(resourceWriter); return (uint)result; } private static uint GetManagedResourceOffset(BlobBuilder resource, BlobBuilder resourceWriter) { int result = resourceWriter.Count; resourceWriter.WriteInt32(resource.Count); resource.WriteContentTo(resourceWriter); resourceWriter.Align(8); return (uint)result; } public static string GetMangledName(INamedTypeReference namedType, int generation) { string unmangledName = (generation == 0) ? namedType.Name : namedType.Name + "#" + generation; return namedType.MangleName ? MetadataHelpers.ComposeAritySuffixedMetadataName(unmangledName, namedType.GenericParameterCount) : unmangledName; } internal MemberReferenceHandle GetMemberReferenceHandle(ITypeMemberReference memberRef) { return this.GetOrAddMemberReferenceHandle(memberRef); } internal EntityHandle GetMemberReferenceParent(ITypeMemberReference memberRef) { ITypeDefinition parentTypeDef = memberRef.GetContainingType(Context).AsTypeDefinition(Context); if (parentTypeDef != null) { TypeDefinitionHandle parentTypeDefHandle; TryGetTypeDefinitionHandle(parentTypeDef, out parentTypeDefHandle); if (!parentTypeDefHandle.IsNil) { if (memberRef is IFieldReference) { return parentTypeDefHandle; } if (memberRef is IMethodReference methodRef) { if (methodRef.AcceptsExtraArguments) { MethodDefinitionHandle methodHandle; if (this.TryGetMethodDefinitionHandle(methodRef.GetResolvedMethod(Context), out methodHandle)) { return methodHandle; } } return parentTypeDefHandle; } // TODO: error } } // TODO: special treatment for global fields and methods. Object model support would be nice. var containingType = memberRef.GetContainingType(Context); return containingType.IsTypeSpecification() ? (EntityHandle)GetTypeSpecificationHandle(containingType) : GetTypeReferenceHandle(containingType); } internal EntityHandle GetMethodDefinitionOrReferenceHandle(IMethodReference methodReference) { IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } return methodDef != null ? (EntityHandle)GetMethodDefinitionHandle(methodDef) : GetMemberReferenceHandle(methodReference); } public static MethodAttributes GetMethodAttributes(IMethodDefinition methodDef) { var result = (MethodAttributes)methodDef.Visibility; if (methodDef.IsStatic) { result |= MethodAttributes.Static; } if (methodDef.IsSealed) { result |= MethodAttributes.Final; } if (methodDef.IsVirtual) { result |= MethodAttributes.Virtual; } if (methodDef.IsHiddenBySignature) { result |= MethodAttributes.HideBySig; } if (methodDef.IsNewSlot) { result |= MethodAttributes.NewSlot; } if (methodDef.IsAccessCheckedOnOverride) { result |= MethodAttributes.CheckAccessOnOverride; } if (methodDef.IsAbstract) { result |= MethodAttributes.Abstract; } if (methodDef.IsSpecialName) { result |= MethodAttributes.SpecialName; } if (methodDef.IsRuntimeSpecial) { result |= MethodAttributes.RTSpecialName; } if (methodDef.IsPlatformInvoke) { result |= MethodAttributes.PinvokeImpl; } if (methodDef.HasDeclarativeSecurity) { result |= MethodAttributes.HasSecurity; } if (methodDef.RequiresSecurityObject) { result |= MethodAttributes.RequireSecObject; } return result; } internal BlobHandle GetMethodSpecificationSignatureHandle(IGenericMethodInstanceReference methodInstanceReference) { BlobHandle result; if (_methodInstanceSignatureIndex.TryGetValue(methodInstanceReference, out result)) { return result; } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).MethodSpecificationSignature(methodInstanceReference.GetGenericMethod(Context).GenericParameterCount); foreach (ITypeReference typeReference in methodInstanceReference.GetGenericArguments(Context)) { var typeRef = typeReference; SerializeTypeReference(encoder.AddArgument(), typeRef); } result = metadata.GetOrAddBlob(builder); _methodInstanceSignatureIndex.Add(methodInstanceReference, result); builder.Free(); return result; } private BlobHandle GetMarshallingDescriptorHandle(IMarshallingInformation marshallingInformation) { BlobHandle result; if (_marshallingDescriptorIndex.TryGetValue(marshallingInformation, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeMarshallingDescriptor(marshallingInformation, writer); result = metadata.GetOrAddBlob(writer); _marshallingDescriptorIndex.Add(marshallingInformation, result); writer.Free(); return result; } private BlobHandle GetMarshallingDescriptorHandle(ImmutableArray<byte> descriptor) { return metadata.GetOrAddBlob(descriptor); } private BlobHandle GetMemberReferenceSignatureHandle(ITypeMemberReference memberRef) { return memberRef switch { IFieldReference fieldReference => this.GetFieldSignatureIndex(fieldReference), IMethodReference methodReference => this.GetMethodSignatureHandle(methodReference), _ => throw ExceptionUtilities.Unreachable }; } internal BlobHandle GetMethodSignatureHandle(IMethodReference methodReference) { return GetMethodSignatureHandleAndBlob(methodReference, out _); } internal byte[] GetMethodSignature(IMethodReference methodReference) { ImmutableArray<byte> signatureBlob; GetMethodSignatureHandleAndBlob(methodReference, out signatureBlob); return signatureBlob.ToArray(); } private BlobHandle GetMethodSignatureHandleAndBlob(IMethodReference methodReference, out ImmutableArray<byte> signatureBlob) { BlobHandle result; ISpecializedMethodReference specializedMethodReference = methodReference.AsSpecializedMethodReference; if (specializedMethodReference != null) { methodReference = specializedMethodReference.UnspecializedVersion; } KeyValuePair<BlobHandle, ImmutableArray<byte>> existing; if (_signatureIndex.TryGetValue(methodReference, out existing)) { signatureBlob = existing.Value; return existing.Key; } Debug.Assert((methodReference.CallingConvention & CallingConvention.Generic) != 0 == (methodReference.GenericParameterCount > 0)); var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).MethodSignature( new SignatureHeader((byte)methodReference.CallingConvention).CallingConvention, methodReference.GenericParameterCount, isInstanceMethod: (methodReference.CallingConvention & CallingConvention.HasThis) != 0); SerializeReturnValueAndParameters(encoder, methodReference, methodReference.ExtraParameters); signatureBlob = builder.ToImmutableArray(); result = metadata.GetOrAddBlob(signatureBlob); _signatureIndex.Add(methodReference, KeyValuePairUtil.Create(result, signatureBlob)); builder.Free(); return result; } private BlobHandle GetMethodSpecificationBlobHandle(IGenericMethodInstanceReference genericMethodInstanceReference) { var writer = PooledBlobBuilder.GetInstance(); SerializeMethodSpecificationSignature(writer, genericMethodInstanceReference); BlobHandle result = metadata.GetOrAddBlob(writer); writer.Free(); return result; } private MethodSpecificationHandle GetMethodSpecificationHandle(IGenericMethodInstanceReference methodSpec) { return this.GetOrAddMethodSpecificationHandle(methodSpec); } internal EntityHandle GetMethodHandle(IMethodReference methodReference) { MethodDefinitionHandle methodDefHandle; IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } if (methodDef != null && (methodReference == methodDef || !methodReference.AcceptsExtraArguments) && this.TryGetMethodDefinitionHandle(methodDef, out methodDefHandle)) { return methodDefHandle; } IGenericMethodInstanceReference methodSpec = methodReference.AsGenericMethodInstanceReference; return methodSpec != null ? (EntityHandle)GetMethodSpecificationHandle(methodSpec) : GetMemberReferenceHandle(methodReference); } internal EntityHandle GetStandaloneSignatureHandle(ISignature signature) { Debug.Assert(!(signature is IMethodReference)); var builder = PooledBlobBuilder.GetInstance(); var signatureEncoder = new BlobEncoder(builder).MethodSignature(convention: signature.CallingConvention.ToSignatureConvention(), genericParameterCount: 0, isInstanceMethod: false); SerializeReturnValueAndParameters(signatureEncoder, signature, varargParameters: ImmutableArray<IParameterTypeInformation>.Empty); BlobHandle blobIndex = metadata.GetOrAddBlob(builder); StandaloneSignatureHandle handle = GetOrAddStandaloneSignatureHandle(blobIndex); return handle; } public static ParameterAttributes GetParameterAttributes(IParameterDefinition parDef) { ParameterAttributes result = 0; if (parDef.IsIn) { result |= ParameterAttributes.In; } if (parDef.IsOut) { result |= ParameterAttributes.Out; } if (parDef.IsOptional) { result |= ParameterAttributes.Optional; } if (parDef.HasDefaultValue) { result |= ParameterAttributes.HasDefault; } if (parDef.IsMarshalledExplicitly) { result |= ParameterAttributes.HasFieldMarshal; } return result; } private BlobHandle GetPermissionSetBlobHandle(ImmutableArray<ICustomAttribute> permissionSet) { var writer = PooledBlobBuilder.GetInstance(); BlobHandle result; try { writer.WriteByte((byte)'.'); writer.WriteCompressedInteger(permissionSet.Length); this.SerializePermissionSet(permissionSet, writer); result = metadata.GetOrAddBlob(writer); } finally { writer.Free(); } return result; } public static PropertyAttributes GetPropertyAttributes(IPropertyDefinition propertyDef) { PropertyAttributes result = 0; if (propertyDef.IsSpecialName) { result |= PropertyAttributes.SpecialName; } if (propertyDef.IsRuntimeSpecial) { result |= PropertyAttributes.RTSpecialName; } if (propertyDef.HasDefaultValue) { result |= PropertyAttributes.HasDefault; } return result; } private BlobHandle GetPropertySignatureHandle(IPropertyDefinition propertyDef) { KeyValuePair<BlobHandle, ImmutableArray<byte>> existing; if (_signatureIndex.TryGetValue(propertyDef, out existing)) { return existing.Key; } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).PropertySignature( isInstanceProperty: (propertyDef.CallingConvention & CallingConvention.HasThis) != 0); SerializeReturnValueAndParameters(encoder, propertyDef, ImmutableArray<IParameterTypeInformation>.Empty); var blob = builder.ToImmutableArray(); var result = metadata.GetOrAddBlob(blob); _signatureIndex.Add(propertyDef, KeyValuePairUtil.Create(result, blob)); builder.Free(); return result; } private EntityHandle GetResolutionScopeHandle(IUnitReference unitReference) { if (unitReference is IAssemblyReference aref) { return GetAssemblyReferenceHandle(aref); } // If this is a module from a referenced multi-module assembly, // the assembly should be used as the resolution scope. var mref = (IModuleReference)unitReference; aref = mref.GetContainingAssembly(Context); if (aref != null && aref != module.GetContainingAssembly(Context)) { return GetAssemblyReferenceHandle(aref); } return GetModuleReferenceHandle(mref.Name); } private StringHandle GetStringHandleForPathAndCheckLength(string path, INamedEntity errorEntity = null) { CheckPathLength(path, errorEntity); return metadata.GetOrAddString(path); } private StringHandle GetStringHandleForNameAndCheckLength(string name, INamedEntity errorEntity = null) { CheckNameLength(name, errorEntity); return metadata.GetOrAddString(name); } /// <summary> /// The Microsoft CLR requires that {namespace} + "." + {name} fit in MAX_CLASS_NAME /// (even though the name and namespace are stored separately in the Microsoft /// implementation). Note that the namespace name of a nested type is always blank /// (since comes from the container). /// </summary> /// <param name="namespaceType">We're trying to add the containing namespace of this type to the string heap.</param> /// <param name="mangledTypeName">Namespace names are never used on their own - this is the type that is adding the namespace name. /// Used only for length checking.</param> private StringHandle GetStringHandleForNamespaceAndCheckLength(INamespaceTypeReference namespaceType, string mangledTypeName) { string namespaceName = namespaceType.NamespaceName; if (namespaceName.Length == 0) // Optimization: CheckNamespaceLength is relatively expensive. { return default(StringHandle); } CheckNamespaceLength(namespaceName, mangledTypeName, namespaceType); return metadata.GetOrAddString(namespaceName); } private void CheckNameLength(string name, INamedEntity errorEntity) { // NOTE: ildasm shows quotes around some names (e.g. explicit implementations of members of generic interfaces) // but that seems to be tool-specific - they don't seem to and up in the string heap (so they don't count against // the length limit). if (IsTooLongInternal(name, NameLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, name)); } } private void CheckPathLength(string path, INamedEntity errorEntity = null) { if (IsTooLongInternal(path, PathLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, path)); } } private void CheckNamespaceLength(string namespaceName, string mangledTypeName, INamespaceTypeReference errorEntity) { // It's never useful to report that the namespace name is too long. // If it's too long, then the full name is too long and that string is // more helpful. // PERF: We expect to check this A LOT, so we'll aggressively inline some // of the helpers (esp IsTooLongInternal) in a way that allows us to forego // string concatenation (unless a diagnostic is actually reported). if (namespaceName.Length + 1 + mangledTypeName.Length > NameLengthLimit / 3) { int utf8Length = s_utf8Encoding.GetByteCount(namespaceName) + 1 + // dot s_utf8Encoding.GetByteCount(mangledTypeName); if (utf8Length > NameLengthLimit) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, namespaceName + "." + mangledTypeName)); } } } internal bool IsUsingStringTooLong(string usingString, INamedEntity errorEntity = null) { if (IsTooLongInternal(usingString, PdbLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.WRN_PdbUsingNameTooLong, location, usingString)); return true; } return false; } internal bool IsLocalNameTooLong(ILocalDefinition localDefinition) { string name = localDefinition.Name; if (IsTooLongInternal(name, PdbLengthLimit)) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.WRN_PdbLocalNameTooLong, localDefinition.Location, name)); return true; } return false; } /// <summary> /// Test the given name to see if it fits in metadata. /// </summary> /// <param name="str">String to test (non-null).</param> /// <param name="maxLength">Max length for name. (Expected to be at least 5.)</param> /// <returns>True if the name is too long.</returns> /// <remarks>Internal for test purposes.</remarks> internal static bool IsTooLongInternal(string str, int maxLength) { Debug.Assert(str != null); // No need to handle in an internal utility. if (str.Length < maxLength / 3) //UTF-8 uses at most 3 bytes per char { return false; } int utf8Length = s_utf8Encoding.GetByteCount(str); return utf8Length > maxLength; } private static Location GetNamedEntityLocation(INamedEntity errorEntity) { ISymbolInternal symbol; if (errorEntity is Cci.INamespace ns) { symbol = ns.GetInternalSymbol(); } else { symbol = (errorEntity as Cci.IReference)?.GetInternalSymbol(); } return GetSymbolLocation(symbol); } protected static Location GetSymbolLocation(ISymbolInternal symbolOpt) { return symbolOpt != null && !symbolOpt.Locations.IsDefaultOrEmpty ? symbolOpt.Locations[0] : Location.None; } internal TypeAttributes GetTypeAttributes(ITypeDefinition typeDef) { return GetTypeAttributes(typeDef, Context); } public static TypeAttributes GetTypeAttributes(ITypeDefinition typeDef, EmitContext context) { TypeAttributes result = 0; switch (typeDef.Layout) { case LayoutKind.Sequential: result |= TypeAttributes.SequentialLayout; break; case LayoutKind.Explicit: result |= TypeAttributes.ExplicitLayout; break; } if (typeDef.IsInterface) { result |= TypeAttributes.Interface; } if (typeDef.IsAbstract) { result |= TypeAttributes.Abstract; } if (typeDef.IsSealed) { result |= TypeAttributes.Sealed; } if (typeDef.IsSpecialName) { result |= TypeAttributes.SpecialName; } if (typeDef.IsRuntimeSpecial) { result |= TypeAttributes.RTSpecialName; } if (typeDef.IsComObject) { result |= TypeAttributes.Import; } if (typeDef.IsSerializable) { result |= TypeAttributes.Serializable; } if (typeDef.IsWindowsRuntimeImport) { result |= TypeAttributes.WindowsRuntime; } switch (typeDef.StringFormat) { case CharSet.Unicode: result |= TypeAttributes.UnicodeClass; break; case Constants.CharSet_Auto: result |= TypeAttributes.AutoClass; break; } if (typeDef.HasDeclarativeSecurity) { result |= TypeAttributes.HasSecurity; } if (typeDef.IsBeforeFieldInit) { result |= TypeAttributes.BeforeFieldInit; } INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(context); if (nestedTypeDef != null) { switch (((ITypeDefinitionMember)typeDef).Visibility) { case TypeMemberVisibility.Public: result |= TypeAttributes.NestedPublic; break; case TypeMemberVisibility.Private: result |= TypeAttributes.NestedPrivate; break; case TypeMemberVisibility.Family: result |= TypeAttributes.NestedFamily; break; case TypeMemberVisibility.Assembly: result |= TypeAttributes.NestedAssembly; break; case TypeMemberVisibility.FamilyAndAssembly: result |= TypeAttributes.NestedFamANDAssem; break; case TypeMemberVisibility.FamilyOrAssembly: result |= TypeAttributes.NestedFamORAssem; break; } return result; } INamespaceTypeDefinition namespaceTypeDef = typeDef.AsNamespaceTypeDefinition(context); if (namespaceTypeDef != null && namespaceTypeDef.IsPublic) { result |= TypeAttributes.Public; } return result; } private EntityHandle GetDeclaringTypeOrMethodHandle(IGenericParameter genPar) { IGenericTypeParameter genTypePar = genPar.AsGenericTypeParameter; if (genTypePar != null) { return GetTypeDefinitionHandle(genTypePar.DefiningType); } IGenericMethodParameter genMethPar = genPar.AsGenericMethodParameter; if (genMethPar != null) { return GetMethodDefinitionHandle(genMethPar.DefiningMethod); } throw ExceptionUtilities.Unreachable; } private TypeReferenceHandle GetTypeReferenceHandle(ITypeReference typeReference) { TypeReferenceHandle result; if (this.TryGetTypeReferenceHandle(typeReference, out result)) { return result; } // NOTE: Even though CLR documentation does not explicitly specify any requirements // NOTE: to the order of records in TypeRef table, some tools and/or APIs (e.g. // NOTE: IMetaDataEmit::MergeEnd) assume that the containing type referenced as // NOTE: ResolutionScope for its nested types should appear in TypeRef table // NOTE: *before* any of its nested types. // SEE ALSO: bug#570975 and test Bug570975() INestedTypeReference nestedTypeRef = typeReference.AsNestedTypeReference; if (nestedTypeRef != null) { GetTypeReferenceHandle(nestedTypeRef.GetContainingType(this.Context)); } return this.GetOrAddTypeReferenceHandle(typeReference); } private TypeSpecificationHandle GetTypeSpecificationHandle(ITypeReference typeReference) { return this.GetOrAddTypeSpecificationHandle(typeReference); } internal ITypeDefinition GetTypeDefinition(int token) { // The token must refer to a TypeDef row since we are // only handling indexes into the full metadata (in EnC) // for def tables. Other tables contain deltas only. return GetTypeDef(MetadataTokens.TypeDefinitionHandle(token)); } internal IMethodDefinition GetMethodDefinition(int token) { // Must be a def table. (See comment in GetTypeDefinition.) return GetMethodDef(MetadataTokens.MethodDefinitionHandle(token)); } internal INestedTypeReference GetNestedTypeReference(int token) { // Must be a def table. (See comment in GetTypeDefinition.) return GetTypeDef(MetadataTokens.TypeDefinitionHandle(token)).AsNestedTypeReference; } internal BlobHandle GetTypeSpecSignatureIndex(ITypeReference typeReference) { BlobHandle result; if (_typeSpecSignatureIndex.TryGetValue(typeReference, out result)) { return result; } var builder = PooledBlobBuilder.GetInstance(); this.SerializeTypeReference(new BlobEncoder(builder).TypeSpecificationSignature(), typeReference); result = metadata.GetOrAddBlob(builder); _typeSpecSignatureIndex.Add(typeReference, result); builder.Free(); return result; } internal EntityHandle GetTypeHandle(ITypeReference typeReference, bool treatRefAsPotentialTypeSpec = true) { TypeDefinitionHandle handle; var typeDefinition = typeReference.AsTypeDefinition(this.Context); if (typeDefinition != null && this.TryGetTypeDefinitionHandle(typeDefinition, out handle)) { return handle; } return treatRefAsPotentialTypeSpec && typeReference.IsTypeSpecification() ? (EntityHandle)GetTypeSpecificationHandle(typeReference) : GetTypeReferenceHandle(typeReference); } internal EntityHandle GetDefinitionHandle(IDefinition definition) { return definition switch { ITypeDefinition typeDef => (EntityHandle)GetTypeDefinitionHandle(typeDef), IMethodDefinition methodDef => GetMethodDefinitionHandle(methodDef), IFieldDefinition fieldDef => GetFieldDefinitionHandle(fieldDef), IEventDefinition eventDef => GetEventDefinitionHandle(eventDef), IPropertyDefinition propertyDef => GetPropertyDefIndex(propertyDef), _ => throw ExceptionUtilities.Unreachable }; } public void WriteMetadataAndIL(PdbWriter nativePdbWriterOpt, Stream metadataStream, Stream ilStream, Stream portablePdbStreamOpt, out MetadataSizes metadataSizes) { Debug.Assert(nativePdbWriterOpt == null ^ portablePdbStreamOpt == null); nativePdbWriterOpt?.SetMetadataEmitter(this); // TODO: we can precalculate the exact size of IL stream var ilBuilder = new BlobBuilder(1024); var metadataBuilder = new BlobBuilder(4 * 1024); var mappedFieldDataBuilder = new BlobBuilder(0); var managedResourceDataBuilder = new BlobBuilder(0); // Add 4B of padding to the start of the separated IL stream, // so that method RVAs, which are offsets to this stream, are never 0. ilBuilder.WriteUInt32(0); // this is used to handle edit-and-continue emit, so we should have a module // version ID that is imposed by the caller (the same as the previous module version ID). // Therefore we do not have to fill in a new module version ID in the generated metadata // stream. Debug.Assert(module.SerializationProperties.PersistentIdentifier != default(Guid)); BuildMetadataAndIL( nativePdbWriterOpt, ilBuilder, mappedFieldDataBuilder, managedResourceDataBuilder, out Blob mvidFixup, out Blob mvidStringFixup); var typeSystemRowCounts = metadata.GetRowCounts(); Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncLog] == 0); Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncMap] == 0); PopulateEncTables(typeSystemRowCounts); Debug.Assert(mappedFieldDataBuilder.Count == 0); Debug.Assert(managedResourceDataBuilder.Count == 0); Debug.Assert(mvidFixup.IsDefault); Debug.Assert(mvidStringFixup.IsDefault); // TODO (https://github.com/dotnet/roslyn/issues/3905): // InterfaceImpl table emitted by Roslyn is not compliant with ECMA spec. // Once fixed enable validation in DEBUG builds. var rootBuilder = new MetadataRootBuilder(metadata, module.SerializationProperties.TargetRuntimeVersion, suppressValidation: true); rootBuilder.Serialize(metadataBuilder, methodBodyStreamRva: 0, mappedFieldDataStreamRva: 0); metadataSizes = rootBuilder.Sizes; try { ilBuilder.WriteContentTo(ilStream); metadataBuilder.WriteContentTo(metadataStream); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new PeWritingException(e); } if (portablePdbStreamOpt != null) { var portablePdbBuilder = GetPortablePdbBuilder( typeSystemRowCounts, debugEntryPoint: default(MethodDefinitionHandle), deterministicIdProviderOpt: null); var portablePdbBlob = new BlobBuilder(); portablePdbBuilder.Serialize(portablePdbBlob); try { portablePdbBlob.WriteContentTo(portablePdbStreamOpt); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new SymUnmanagedWriterException(e.Message, e); } } } public void BuildMetadataAndIL( PdbWriter nativePdbWriterOpt, BlobBuilder ilBuilder, BlobBuilder mappedFieldDataBuilder, BlobBuilder managedResourceDataBuilder, out Blob mvidFixup, out Blob mvidStringFixup) { // Extract information from object model into tables, indices and streams CreateIndices(); if (_debugMetadataOpt != null) { // Ensure document table lists files in command line order // This is key for us to be able to accurately rebuild a binary from a PDB. var documentsBuilder = Module.DebugDocumentsBuilder; foreach (var tree in Module.CommonCompilation.SyntaxTrees) { if (documentsBuilder.TryGetDebugDocument(tree.FilePath, basePath: null) is { } doc && !_documentIndex.ContainsKey(doc)) { AddDocument(doc, _documentIndex); } } if (Context.RebuildData is { } rebuildData) { _usingNonSourceDocumentNameEnumerator = true; _nonSourceDocumentNameEnumerator = rebuildData.NonSourceFileDocumentNames.GetEnumerator(); } DefineModuleImportScope(); if (module.SourceLinkStreamOpt != null) { EmbedSourceLink(module.SourceLinkStreamOpt); } EmbedCompilationOptions(module); EmbedMetadataReferenceInformation(module); } int[] methodBodyOffsets; if (MetadataOnly) { methodBodyOffsets = SerializeThrowNullMethodBodies(ilBuilder); mvidStringFixup = default(Blob); } else { methodBodyOffsets = SerializeMethodBodies(ilBuilder, nativePdbWriterOpt, out mvidStringFixup); } _cancellationToken.ThrowIfCancellationRequested(); // method body serialization adds Stand Alone Signatures _tableIndicesAreComplete = true; ReportReferencesToAddedSymbols(); BlobBuilder dynamicAnalysisDataOpt = null; if (_dynamicAnalysisDataWriterOpt != null) { dynamicAnalysisDataOpt = new BlobBuilder(); _dynamicAnalysisDataWriterOpt.SerializeMetadataTables(dynamicAnalysisDataOpt); } PopulateTypeSystemTables(methodBodyOffsets, mappedFieldDataBuilder, managedResourceDataBuilder, dynamicAnalysisDataOpt, out mvidFixup); } public virtual void PopulateEncTables(ImmutableArray<int> typeSystemRowCounts) { } public MetadataRootBuilder GetRootBuilder() { // TODO (https://github.com/dotnet/roslyn/issues/3905): // InterfaceImpl table emitted by Roslyn is not compliant with ECMA spec. // Once fixed enable validation in DEBUG builds. return new MetadataRootBuilder(metadata, module.SerializationProperties.TargetRuntimeVersion, suppressValidation: true); } public PortablePdbBuilder GetPortablePdbBuilder(ImmutableArray<int> typeSystemRowCounts, MethodDefinitionHandle debugEntryPoint, Func<IEnumerable<Blob>, BlobContentId> deterministicIdProviderOpt) { return new PortablePdbBuilder(_debugMetadataOpt, typeSystemRowCounts, debugEntryPoint, deterministicIdProviderOpt); } internal void GetEntryPoints(out MethodDefinitionHandle entryPointHandle, out MethodDefinitionHandle debugEntryPointHandle) { if (IsFullMetadata && !MetadataOnly) { // PE entry point is set for executable programs IMethodReference entryPoint = module.PEEntryPoint; entryPointHandle = entryPoint != null ? (MethodDefinitionHandle)GetMethodHandle((IMethodDefinition)entryPoint.AsDefinition(Context)) : default(MethodDefinitionHandle); // debug entry point may be different from PE entry point, it may also be set for libraries IMethodReference debugEntryPoint = module.DebugEntryPoint; if (debugEntryPoint != null && debugEntryPoint != entryPoint) { debugEntryPointHandle = (MethodDefinitionHandle)GetMethodHandle((IMethodDefinition)debugEntryPoint.AsDefinition(Context)); } else { debugEntryPointHandle = entryPointHandle; } } else { entryPointHandle = debugEntryPointHandle = default(MethodDefinitionHandle); } } private ImmutableArray<IGenericParameter> GetSortedGenericParameters() { return GetGenericParameters().OrderBy((x, y) => { // Spec: GenericParam table is sorted by Owner and then by Number. int result = CodedIndex.TypeOrMethodDef(GetDeclaringTypeOrMethodHandle(x)) - CodedIndex.TypeOrMethodDef(GetDeclaringTypeOrMethodHandle(y)); if (result != 0) { return result; } return x.Index - y.Index; }).ToImmutableArray(); } private void PopulateTypeSystemTables(int[] methodBodyOffsets, BlobBuilder mappedFieldDataWriter, BlobBuilder resourceWriter, BlobBuilder dynamicAnalysisDataOpt, out Blob mvidFixup) { var sortedGenericParameters = GetSortedGenericParameters(); this.PopulateAssemblyRefTableRows(); this.PopulateAssemblyTableRows(); this.PopulateClassLayoutTableRows(); this.PopulateConstantTableRows(); this.PopulateDeclSecurityTableRows(); this.PopulateEventMapTableRows(); this.PopulateEventTableRows(); this.PopulateExportedTypeTableRows(); this.PopulateFieldLayoutTableRows(); this.PopulateFieldMarshalTableRows(); this.PopulateFieldRvaTableRows(mappedFieldDataWriter); this.PopulateFieldTableRows(); this.PopulateFileTableRows(); this.PopulateGenericParameters(sortedGenericParameters); this.PopulateImplMapTableRows(); this.PopulateInterfaceImplTableRows(); this.PopulateManifestResourceTableRows(resourceWriter, dynamicAnalysisDataOpt); this.PopulateMemberRefTableRows(); this.PopulateMethodImplTableRows(); this.PopulateMethodTableRows(methodBodyOffsets); this.PopulateMethodSemanticsTableRows(); this.PopulateMethodSpecTableRows(); this.PopulateModuleRefTableRows(); this.PopulateModuleTableRow(out mvidFixup); this.PopulateNestedClassTableRows(); this.PopulateParamTableRows(); this.PopulatePropertyMapTableRows(); this.PopulatePropertyTableRows(); this.PopulateTypeDefTableRows(); this.PopulateTypeRefTableRows(); this.PopulateTypeSpecTableRows(); this.PopulateStandaloneSignatures(); // This table is populated after the others because it depends on the order of the entries of the generic parameter table. this.PopulateCustomAttributeTableRows(sortedGenericParameters); } private void PopulateAssemblyRefTableRows() { var assemblyRefs = this.GetAssemblyRefs(); metadata.SetCapacity(TableIndex.AssemblyRef, assemblyRefs.Count); foreach (var identity in assemblyRefs) { // reference has token, not full public key metadata.AddAssemblyReference( name: GetStringHandleForPathAndCheckLength(identity.Name), version: identity.Version, culture: metadata.GetOrAddString(identity.CultureName), publicKeyOrToken: metadata.GetOrAddBlob(identity.PublicKeyToken), flags: (AssemblyFlags)((int)identity.ContentType << 9) | (identity.IsRetargetable ? AssemblyFlags.Retargetable : 0), hashValue: default(BlobHandle)); } } private void PopulateAssemblyTableRows() { if (!EmitAssemblyDefinition) { return; } var sourceAssembly = module.SourceAssemblyOpt; Debug.Assert(sourceAssembly != null); var flags = sourceAssembly.AssemblyFlags & ~AssemblyFlags.PublicKey; if (!sourceAssembly.Identity.PublicKey.IsDefaultOrEmpty) { flags |= AssemblyFlags.PublicKey; } metadata.AddAssembly( flags: flags, hashAlgorithm: sourceAssembly.HashAlgorithm, version: sourceAssembly.Identity.Version, publicKey: metadata.GetOrAddBlob(sourceAssembly.Identity.PublicKey), name: GetStringHandleForPathAndCheckLength(module.Name, module), culture: metadata.GetOrAddString(sourceAssembly.Identity.CultureName)); } private void PopulateCustomAttributeTableRows(ImmutableArray<IGenericParameter> sortedGenericParameters) { if (this.IsFullMetadata) { this.AddAssemblyAttributesToTable(); } this.AddCustomAttributesToTable(GetMethodDefs(), def => GetMethodDefinitionHandle(def)); this.AddCustomAttributesToTable(GetFieldDefs(), def => GetFieldDefinitionHandle(def)); // this.AddCustomAttributesToTable(this.typeRefList, 2); var typeDefs = GetTypeDefs(); this.AddCustomAttributesToTable(typeDefs, def => GetTypeDefinitionHandle(def)); this.AddCustomAttributesToTable(GetParameterDefs(), def => GetParameterHandle(def)); // TODO: attributes on member reference entries 6 if (this.IsFullMetadata) { this.AddModuleAttributesToTable(module); } // TODO: declarative security entries 8 this.AddCustomAttributesToTable(GetPropertyDefs(), def => GetPropertyDefIndex(def)); this.AddCustomAttributesToTable(GetEventDefs(), def => GetEventDefinitionHandle(def)); // TODO: standalone signature entries 11 // TODO: type spec entries 13 // this.AddCustomAttributesToTable(this.module.AssemblyReferences, 15); // TODO: this.AddCustomAttributesToTable(assembly.Files, 16); // TODO: exported types 17 // TODO: this.AddCustomAttributesToTable(assembly.Resources, 18); this.AddCustomAttributesToTable(sortedGenericParameters, TableIndex.GenericParam); } private void AddAssemblyAttributesToTable() { bool writingNetModule = module.OutputKind == OutputKind.NetModule; if (writingNetModule) { // When writing netmodules, assembly security attributes are not emitted by PopulateDeclSecurityTableRows(). // Instead, here we make sure they are emitted as regular attributes, attached off the appropriate placeholder // System.Runtime.CompilerServices.AssemblyAttributesGoHere* type refs. This is the contract for publishing // assembly attributes in netmodules so they may be migrated to containing/referencing multi-module assemblies, // at multi-module assembly build time. AddAssemblyAttributesToTable( this.module.GetSourceAssemblySecurityAttributes().Select(sa => sa.Attribute), needsDummyParent: true, isSecurity: true); } AddAssemblyAttributesToTable( this.module.GetSourceAssemblyAttributes(Context.IsRefAssembly), needsDummyParent: writingNetModule, isSecurity: false); } private void AddAssemblyAttributesToTable(IEnumerable<ICustomAttribute> assemblyAttributes, bool needsDummyParent, bool isSecurity) { Debug.Assert(this.IsFullMetadata); // parentToken is not relative EntityHandle parentHandle = Handle.AssemblyDefinition; foreach (ICustomAttribute customAttribute in assemblyAttributes) { if (needsDummyParent) { // When writing netmodules, assembly attributes are attached off the appropriate placeholder // System.Runtime.CompilerServices.AssemblyAttributesGoHere* type refs. This is the contract for publishing // assembly attributes in netmodules so they may be migrated to containing/referencing multi-module assemblies, // at multi-module assembly build time. parentHandle = GetDummyAssemblyAttributeParent(isSecurity, customAttribute.AllowMultiple); } AddCustomAttributeToTable(parentHandle, customAttribute); } } private TypeReferenceHandle GetDummyAssemblyAttributeParent(bool isSecurity, bool allowMultiple) { // Lazily get or create placeholder assembly attribute parent type ref for the given combination of // whether isSecurity and allowMultiple. Convert type ref row id to corresponding attribute parent tag. // Note that according to the defacto contract, although the placeholder type refs have CorLibrary as their // resolution scope, the types backing the placeholder type refs need not actually exist. int iS = isSecurity ? 1 : 0; int iM = allowMultiple ? 1 : 0; if (_dummyAssemblyAttributeParent[iS, iM].IsNil) { _dummyAssemblyAttributeParent[iS, iM] = metadata.AddTypeReference( resolutionScope: GetResolutionScopeHandle(module.GetCorLibrary(Context)), @namespace: metadata.GetOrAddString(dummyAssemblyAttributeParentNamespace), name: metadata.GetOrAddString(dummyAssemblyAttributeParentName + dummyAssemblyAttributeParentQualifier[iS, iM])); } return _dummyAssemblyAttributeParent[iS, iM]; } private void AddModuleAttributesToTable(CommonPEModuleBuilder module) { Debug.Assert(this.IsFullMetadata); AddCustomAttributesToTable(EntityHandle.ModuleDefinition, module.GetSourceModuleAttributes()); } private void AddCustomAttributesToTable<T>(IEnumerable<T> parentList, TableIndex tableIndex) where T : IReference { int parentRowId = 1; foreach (var parent in parentList) { var parentHandle = MetadataTokens.Handle(tableIndex, parentRowId++); AddCustomAttributesToTable(parentHandle, parent.GetAttributes(Context)); } } private void AddCustomAttributesToTable<T>(IEnumerable<T> parentList, Func<T, EntityHandle> getDefinitionHandle) where T : IReference { foreach (var parent in parentList) { EntityHandle parentHandle = getDefinitionHandle(parent); AddCustomAttributesToTable(parentHandle, parent.GetAttributes(Context)); } } protected virtual int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable<ICustomAttribute> attributes) { int count = 0; foreach (var attr in attributes) { count++; AddCustomAttributeToTable(parentHandle, attr); } return count; } private void AddCustomAttributeToTable(EntityHandle parentHandle, ICustomAttribute customAttribute) { IMethodReference constructor = customAttribute.Constructor(Context, reportDiagnostics: true); if (constructor != null) { metadata.AddCustomAttribute( parent: parentHandle, constructor: GetCustomAttributeTypeCodedIndex(constructor), value: GetCustomAttributeSignatureIndex(customAttribute)); } } private void PopulateDeclSecurityTableRows() { if (module.OutputKind != OutputKind.NetModule) { this.PopulateDeclSecurityTableRowsFor(EntityHandle.AssemblyDefinition, module.GetSourceAssemblySecurityAttributes()); } foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { if (!typeDef.HasDeclarativeSecurity) { continue; } this.PopulateDeclSecurityTableRowsFor(GetTypeDefinitionHandle(typeDef), typeDef.SecurityAttributes); } foreach (IMethodDefinition methodDef in this.GetMethodDefs()) { if (!methodDef.HasDeclarativeSecurity) { continue; } this.PopulateDeclSecurityTableRowsFor(GetMethodDefinitionHandle(methodDef), methodDef.SecurityAttributes); } } private void PopulateDeclSecurityTableRowsFor(EntityHandle parentHandle, IEnumerable<SecurityAttribute> attributes) { OrderPreservingMultiDictionary<DeclarativeSecurityAction, ICustomAttribute> groupedSecurityAttributes = null; foreach (SecurityAttribute securityAttribute in attributes) { groupedSecurityAttributes = groupedSecurityAttributes ?? OrderPreservingMultiDictionary<DeclarativeSecurityAction, ICustomAttribute>.GetInstance(); groupedSecurityAttributes.Add(securityAttribute.Action, securityAttribute.Attribute); } if (groupedSecurityAttributes == null) { return; } foreach (DeclarativeSecurityAction securityAction in groupedSecurityAttributes.Keys) { metadata.AddDeclarativeSecurityAttribute( parent: parentHandle, action: securityAction, permissionSet: GetPermissionSetBlobHandle(groupedSecurityAttributes[securityAction])); } groupedSecurityAttributes.Free(); } private void PopulateEventTableRows() { var eventDefs = this.GetEventDefs(); metadata.SetCapacity(TableIndex.Event, eventDefs.Count); foreach (IEventDefinition eventDef in eventDefs) { metadata.AddEvent( attributes: GetEventAttributes(eventDef), name: GetStringHandleForNameAndCheckLength(eventDef.Name, eventDef), type: GetTypeHandle(eventDef.GetType(Context))); } } private void PopulateExportedTypeTableRows() { if (!IsFullMetadata) { return; } var exportedTypes = module.GetExportedTypes(Context.Diagnostics); if (exportedTypes.Length == 0) { return; } metadata.SetCapacity(TableIndex.ExportedType, exportedTypes.Length); foreach (var exportedType in exportedTypes) { INestedTypeReference nestedRef; INamespaceTypeReference namespaceTypeRef; TypeAttributes attributes; StringHandle typeName; StringHandle typeNamespace; EntityHandle implementation; if ((namespaceTypeRef = exportedType.Type.AsNamespaceTypeReference) != null) { // exported types are not emitted in EnC deltas (hence generation 0): string mangledTypeName = GetMangledName(namespaceTypeRef, generation: 0); typeName = GetStringHandleForNameAndCheckLength(mangledTypeName, namespaceTypeRef); typeNamespace = GetStringHandleForNamespaceAndCheckLength(namespaceTypeRef, mangledTypeName); implementation = GetExportedTypeImplementation(namespaceTypeRef); attributes = exportedType.IsForwarder ? TypeAttributes.NotPublic | Constants.TypeAttributes_TypeForwarder : TypeAttributes.Public; } else if ((nestedRef = exportedType.Type.AsNestedTypeReference) != null) { Debug.Assert(exportedType.ParentIndex != -1); // exported types are not emitted in EnC deltas (hence generation 0): string mangledTypeName = GetMangledName(nestedRef, generation: 0); typeName = GetStringHandleForNameAndCheckLength(mangledTypeName, nestedRef); typeNamespace = default(StringHandle); implementation = MetadataTokens.ExportedTypeHandle(exportedType.ParentIndex + 1); attributes = exportedType.IsForwarder ? TypeAttributes.NotPublic : TypeAttributes.NestedPublic; } else { throw ExceptionUtilities.UnexpectedValue(exportedType); } metadata.AddExportedType( attributes: attributes, @namespace: typeNamespace, name: typeName, implementation: implementation, typeDefinitionId: exportedType.IsForwarder ? 0 : MetadataTokens.GetToken(exportedType.Type.TypeDef)); } } private void PopulateFieldLayoutTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (fieldDef.ContainingTypeDefinition.Layout != LayoutKind.Explicit || fieldDef.IsStatic) { continue; } metadata.AddFieldLayout( field: GetFieldDefinitionHandle(fieldDef), offset: fieldDef.Offset); } } private void PopulateFieldMarshalTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (!fieldDef.IsMarshalledExplicitly) { continue; } var marshallingInformation = fieldDef.MarshallingInformation; BlobHandle descriptor = (marshallingInformation != null) ? GetMarshallingDescriptorHandle(marshallingInformation) : GetMarshallingDescriptorHandle(fieldDef.MarshallingDescriptor); metadata.AddMarshallingDescriptor( parent: GetFieldDefinitionHandle(fieldDef), descriptor: descriptor); } foreach (IParameterDefinition parDef in this.GetParameterDefs()) { if (!parDef.IsMarshalledExplicitly) { continue; } var marshallingInformation = parDef.MarshallingInformation; BlobHandle descriptor = (marshallingInformation != null) ? GetMarshallingDescriptorHandle(marshallingInformation) : GetMarshallingDescriptorHandle(parDef.MarshallingDescriptor); metadata.AddMarshallingDescriptor( parent: GetParameterHandle(parDef), descriptor: descriptor); } } private void PopulateFieldRvaTableRows(BlobBuilder mappedFieldDataWriter) { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (fieldDef.MappedData.IsDefault) { continue; } int offset = mappedFieldDataWriter.Count; mappedFieldDataWriter.WriteBytes(fieldDef.MappedData); mappedFieldDataWriter.Align(ManagedPEBuilder.MappedFieldDataAlignment); metadata.AddFieldRelativeVirtualAddress( field: GetFieldDefinitionHandle(fieldDef), offset: offset); } } private void PopulateFieldTableRows() { var fieldDefs = this.GetFieldDefs(); metadata.SetCapacity(TableIndex.Field, fieldDefs.Count); foreach (IFieldDefinition fieldDef in fieldDefs) { if (fieldDef.IsContextualNamedEntity) { ((IContextualNamedEntity)fieldDef).AssociateWithMetadataWriter(this); } metadata.AddFieldDefinition( attributes: GetFieldAttributes(fieldDef), name: GetStringHandleForNameAndCheckLength(fieldDef.Name, fieldDef), signature: GetFieldSignatureIndex(fieldDef)); } } private void PopulateConstantTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { var constant = fieldDef.GetCompileTimeValue(Context); if (constant == null) { continue; } metadata.AddConstant( parent: GetFieldDefinitionHandle(fieldDef), value: constant.Value); } foreach (IParameterDefinition parDef in this.GetParameterDefs()) { var defaultValue = parDef.GetDefaultValue(Context); if (defaultValue == null) { continue; } metadata.AddConstant( parent: GetParameterHandle(parDef), value: defaultValue.Value); } foreach (IPropertyDefinition propDef in this.GetPropertyDefs()) { if (!propDef.HasDefaultValue) { continue; } metadata.AddConstant( parent: GetPropertyDefIndex(propDef), value: propDef.DefaultValue.Value); } } private void PopulateFileTableRows() { ISourceAssemblySymbolInternal assembly = module.SourceAssemblyOpt; if (assembly == null) { return; } var hashAlgorithm = assembly.HashAlgorithm; metadata.SetCapacity(TableIndex.File, _fileRefList.Count); foreach (IFileReference fileReference in _fileRefList) { metadata.AddAssemblyFile( name: GetStringHandleForPathAndCheckLength(fileReference.FileName), hashValue: metadata.GetOrAddBlob(fileReference.GetHashValue(hashAlgorithm)), containsMetadata: fileReference.HasMetadata); } } private void PopulateGenericParameters( ImmutableArray<IGenericParameter> sortedGenericParameters) { foreach (IGenericParameter genericParameter in sortedGenericParameters) { // CONSIDER: The CLI spec doesn't mention a restriction on the Name column of the GenericParam table, // but they go in the same string heap as all the other declaration names, so it stands to reason that // they should be restricted in the same way. var genericParameterHandle = metadata.AddGenericParameter( parent: GetDeclaringTypeOrMethodHandle(genericParameter), attributes: GetGenericParameterAttributes(genericParameter), name: GetStringHandleForNameAndCheckLength(genericParameter.Name, genericParameter), index: genericParameter.Index); foreach (var refWithAttributes in genericParameter.GetConstraints(Context)) { var genericConstraintHandle = metadata.AddGenericParameterConstraint( genericParameter: genericParameterHandle, constraint: GetTypeHandle(refWithAttributes.TypeRef)); AddCustomAttributesToTable(genericConstraintHandle, refWithAttributes.Attributes); } } } private void PopulateImplMapTableRows() { foreach (IMethodDefinition methodDef in this.GetMethodDefs()) { if (!methodDef.IsPlatformInvoke) { continue; } var data = methodDef.PlatformInvokeData; string entryPointName = data.EntryPointName; StringHandle importName = entryPointName != null && entryPointName != methodDef.Name ? GetStringHandleForNameAndCheckLength(entryPointName, methodDef) : metadata.GetOrAddString(methodDef.Name); // Length checked while populating the method def table. metadata.AddMethodImport( method: GetMethodDefinitionHandle(methodDef), attributes: data.Flags, name: importName, module: GetModuleReferenceHandle(data.ModuleName)); } } private void PopulateInterfaceImplTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { var typeDefHandle = GetTypeDefinitionHandle(typeDef); foreach (var interfaceImpl in typeDef.Interfaces(Context)) { var handle = metadata.AddInterfaceImplementation( type: typeDefHandle, implementedInterface: GetTypeHandle(interfaceImpl.TypeRef)); AddCustomAttributesToTable(handle, interfaceImpl.Attributes); } } } private void PopulateManifestResourceTableRows(BlobBuilder resourceDataWriter, BlobBuilder dynamicAnalysisDataOpt) { if (dynamicAnalysisDataOpt != null) { metadata.AddManifestResource( attributes: ManifestResourceAttributes.Private, name: metadata.GetOrAddString("<DynamicAnalysisData>"), implementation: default(EntityHandle), offset: GetManagedResourceOffset(dynamicAnalysisDataOpt, resourceDataWriter) ); } foreach (var resource in this.module.GetResources(Context)) { EntityHandle implementation; if (resource.ExternalFile != null) { // Length checked on insertion into the file table. implementation = GetAssemblyFileHandle(resource.ExternalFile); } else { // This is an embedded resource, we don't support references to resources from referenced assemblies. implementation = default(EntityHandle); } metadata.AddManifestResource( attributes: resource.IsPublic ? ManifestResourceAttributes.Public : ManifestResourceAttributes.Private, name: GetStringHandleForNameAndCheckLength(resource.Name), implementation: implementation, offset: GetManagedResourceOffset(resource, resourceDataWriter)); } // the stream should be aligned: Debug.Assert((resourceDataWriter.Count % ManagedPEBuilder.ManagedResourcesDataAlignment) == 0); } private void PopulateMemberRefTableRows() { var memberRefs = this.GetMemberRefs(); metadata.SetCapacity(TableIndex.MemberRef, memberRefs.Count); foreach (ITypeMemberReference memberRef in memberRefs) { metadata.AddMemberReference( parent: GetMemberReferenceParent(memberRef), name: GetStringHandleForNameAndCheckLength(memberRef.Name, memberRef), signature: GetMemberReferenceSignatureHandle(memberRef)); } } private void PopulateMethodImplTableRows() { metadata.SetCapacity(TableIndex.MethodImpl, methodImplList.Count); foreach (MethodImplementation methodImplementation in this.methodImplList) { metadata.AddMethodImplementation( type: GetTypeDefinitionHandle(methodImplementation.ContainingType), methodBody: GetMethodDefinitionOrReferenceHandle(methodImplementation.ImplementingMethod), methodDeclaration: GetMethodDefinitionOrReferenceHandle(methodImplementation.ImplementedMethod)); } } private void PopulateMethodSpecTableRows() { var methodSpecs = this.GetMethodSpecs(); metadata.SetCapacity(TableIndex.MethodSpec, methodSpecs.Count); foreach (IGenericMethodInstanceReference genericMethodInstanceReference in methodSpecs) { metadata.AddMethodSpecification( method: GetMethodDefinitionOrReferenceHandle(genericMethodInstanceReference.GetGenericMethod(Context)), instantiation: GetMethodSpecificationBlobHandle(genericMethodInstanceReference)); } } private void PopulateMethodTableRows(int[] methodBodyOffsets) { var methodDefs = this.GetMethodDefs(); metadata.SetCapacity(TableIndex.MethodDef, methodDefs.Count); int i = 0; foreach (IMethodDefinition methodDef in methodDefs) { metadata.AddMethodDefinition( attributes: GetMethodAttributes(methodDef), implAttributes: methodDef.GetImplementationAttributes(Context), name: GetStringHandleForNameAndCheckLength(methodDef.Name, methodDef), signature: GetMethodSignatureHandle(methodDef), bodyOffset: methodBodyOffsets[i], parameterList: GetFirstParameterHandle(methodDef)); i++; } } private void PopulateMethodSemanticsTableRows() { var propertyDefs = this.GetPropertyDefs(); var eventDefs = this.GetEventDefs(); // an estimate, not necessarily accurate. metadata.SetCapacity(TableIndex.MethodSemantics, propertyDefs.Count * 2 + eventDefs.Count * 2); foreach (IPropertyDefinition propertyDef in this.GetPropertyDefs()) { var association = GetPropertyDefIndex(propertyDef); foreach (IMethodReference accessorMethod in propertyDef.GetAccessors(Context)) { MethodSemanticsAttributes semantics; if (accessorMethod == propertyDef.Setter) { semantics = MethodSemanticsAttributes.Setter; } else if (accessorMethod == propertyDef.Getter) { semantics = MethodSemanticsAttributes.Getter; } else { semantics = MethodSemanticsAttributes.Other; } metadata.AddMethodSemantics( association: association, semantics: semantics, methodDefinition: GetMethodDefinitionHandle(accessorMethod.GetResolvedMethod(Context))); } } foreach (IEventDefinition eventDef in this.GetEventDefs()) { var association = GetEventDefinitionHandle(eventDef); foreach (IMethodReference accessorMethod in eventDef.GetAccessors(Context)) { MethodSemanticsAttributes semantics; if (accessorMethod == eventDef.Adder) { semantics = MethodSemanticsAttributes.Adder; } else if (accessorMethod == eventDef.Remover) { semantics = MethodSemanticsAttributes.Remover; } else if (accessorMethod == eventDef.Caller) { semantics = MethodSemanticsAttributes.Raiser; } else { semantics = MethodSemanticsAttributes.Other; } metadata.AddMethodSemantics( association: association, semantics: semantics, methodDefinition: GetMethodDefinitionHandle(accessorMethod.GetResolvedMethod(Context))); } } } private void PopulateModuleRefTableRows() { var moduleRefs = this.GetModuleRefs(); metadata.SetCapacity(TableIndex.ModuleRef, moduleRefs.Count); foreach (string moduleName in moduleRefs) { metadata.AddModuleReference(GetStringHandleForPathAndCheckLength(moduleName)); } } private void PopulateModuleTableRow(out Blob mvidFixup) { CheckPathLength(this.module.ModuleName); GuidHandle mvidHandle; Guid mvid = this.module.SerializationProperties.PersistentIdentifier; if (mvid != default(Guid)) { // MVID is specified upfront when emitting EnC delta: mvidHandle = metadata.GetOrAddGuid(mvid); mvidFixup = default(Blob); } else { // The guid will be filled in later: var reservedGuid = metadata.ReserveGuid(); mvidFixup = reservedGuid.Content; mvidHandle = reservedGuid.Handle; reservedGuid.CreateWriter().WriteBytes(0, mvidFixup.Length); } metadata.AddModule( generation: this.Generation, moduleName: metadata.GetOrAddString(this.module.ModuleName), mvid: mvidHandle, encId: metadata.GetOrAddGuid(EncId), encBaseId: metadata.GetOrAddGuid(EncBaseId)); } private void PopulateParamTableRows() { var parameterDefs = this.GetParameterDefs(); metadata.SetCapacity(TableIndex.Param, parameterDefs.Count); foreach (IParameterDefinition parDef in parameterDefs) { metadata.AddParameter( attributes: GetParameterAttributes(parDef), sequenceNumber: (parDef is ReturnValueParameter) ? 0 : parDef.Index + 1, name: GetStringHandleForNameAndCheckLength(parDef.Name, parDef)); } } private void PopulatePropertyTableRows() { var propertyDefs = this.GetPropertyDefs(); metadata.SetCapacity(TableIndex.Property, propertyDefs.Count); foreach (IPropertyDefinition propertyDef in propertyDefs) { metadata.AddProperty( attributes: GetPropertyAttributes(propertyDef), name: GetStringHandleForNameAndCheckLength(propertyDef.Name, propertyDef), signature: GetPropertySignatureHandle(propertyDef)); } } private void PopulateTypeDefTableRows() { var typeDefs = this.GetTypeDefs(); metadata.SetCapacity(TableIndex.TypeDef, typeDefs.Count); foreach (INamedTypeDefinition typeDef in typeDefs) { INamespaceTypeDefinition namespaceType = typeDef.AsNamespaceTypeDefinition(Context); var moduleBuilder = Context.Module; int generation = moduleBuilder.GetTypeDefinitionGeneration(typeDef); string mangledTypeName = GetMangledName(typeDef, generation); ITypeReference baseType = typeDef.GetBaseClass(Context); metadata.AddTypeDefinition( attributes: GetTypeAttributes(typeDef), @namespace: (namespaceType != null) ? GetStringHandleForNamespaceAndCheckLength(namespaceType, mangledTypeName) : default(StringHandle), name: GetStringHandleForNameAndCheckLength(mangledTypeName, typeDef), baseType: (baseType != null) ? GetTypeHandle(baseType) : default(EntityHandle), fieldList: GetFirstFieldDefinitionHandle(typeDef), methodList: GetFirstMethodDefinitionHandle(typeDef)); } } private void PopulateNestedClassTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef == null) { continue; } metadata.AddNestedType( type: GetTypeDefinitionHandle(typeDef), enclosingType: GetTypeDefinitionHandle(nestedTypeDef.ContainingTypeDefinition)); } } private void PopulateClassLayoutTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { if (typeDef.Alignment == 0 && typeDef.SizeOf == 0) { continue; } metadata.AddTypeLayout( type: GetTypeDefinitionHandle(typeDef), packingSize: typeDef.Alignment, size: typeDef.SizeOf); } } private void PopulateTypeRefTableRows() { var typeRefs = this.GetTypeRefs(); metadata.SetCapacity(TableIndex.TypeRef, typeRefs.Count); foreach (ITypeReference typeRef in typeRefs) { EntityHandle resolutionScope; StringHandle name; StringHandle @namespace; INestedTypeReference nestedTypeRef = typeRef.AsNestedTypeReference; if (nestedTypeRef != null) { ITypeReference scopeTypeRef; ISpecializedNestedTypeReference sneTypeRef = nestedTypeRef.AsSpecializedNestedTypeReference; if (sneTypeRef != null) { scopeTypeRef = sneTypeRef.GetUnspecializedVersion(Context).GetContainingType(Context); } else { scopeTypeRef = nestedTypeRef.GetContainingType(Context); } resolutionScope = GetTypeReferenceHandle(scopeTypeRef); // It's not possible to reference newer versions of reloadable types from another assembly, hence generation 0: // TODO: https://github.com/dotnet/roslyn/issues/54981 string mangledTypeName = GetMangledName(nestedTypeRef, generation: 0); name = this.GetStringHandleForNameAndCheckLength(mangledTypeName, nestedTypeRef); @namespace = default(StringHandle); } else { INamespaceTypeReference namespaceTypeRef = typeRef.AsNamespaceTypeReference; if (namespaceTypeRef == null) { throw ExceptionUtilities.UnexpectedValue(typeRef); } resolutionScope = this.GetResolutionScopeHandle(namespaceTypeRef.GetUnit(Context)); // It's not possible to reference newer versions of reloadable types from another assembly, hence generation 0: // TODO: https://github.com/dotnet/roslyn/issues/54981 string mangledTypeName = GetMangledName(namespaceTypeRef, generation: 0); name = this.GetStringHandleForNameAndCheckLength(mangledTypeName, namespaceTypeRef); @namespace = this.GetStringHandleForNamespaceAndCheckLength(namespaceTypeRef, mangledTypeName); } metadata.AddTypeReference( resolutionScope: resolutionScope, @namespace: @namespace, name: name); } } private void PopulateTypeSpecTableRows() { var typeSpecs = this.GetTypeSpecs(); metadata.SetCapacity(TableIndex.TypeSpec, typeSpecs.Count); foreach (ITypeReference typeSpec in typeSpecs) { metadata.AddTypeSpecification(GetTypeSpecSignatureIndex(typeSpec)); } } private void PopulateStandaloneSignatures() { var signatures = GetStandaloneSignatureBlobHandles(); foreach (BlobHandle signature in signatures) { metadata.AddStandaloneSignature(signature); } } private int[] SerializeThrowNullMethodBodies(BlobBuilder ilBuilder) { Debug.Assert(MetadataOnly); var methods = this.GetMethodDefs(); int[] bodyOffsets = new int[methods.Count]; int bodyOffsetCache = -1; int methodRid = 0; foreach (IMethodDefinition method in methods) { if (method.HasBody()) { if (bodyOffsetCache == -1) { bodyOffsetCache = ilBuilder.Count; ilBuilder.WriteBytes(ThrowNullEncodedBody); } bodyOffsets[methodRid] = bodyOffsetCache; } else { bodyOffsets[methodRid] = -1; } methodRid++; } return bodyOffsets; } private int[] SerializeMethodBodies(BlobBuilder ilBuilder, PdbWriter nativePdbWriterOpt, out Blob mvidStringFixup) { CustomDebugInfoWriter customDebugInfoWriter = (nativePdbWriterOpt != null) ? new CustomDebugInfoWriter(nativePdbWriterOpt) : null; var methods = this.GetMethodDefs(); int[] bodyOffsets = new int[methods.Count]; var lastLocalVariableHandle = default(LocalVariableHandle); var lastLocalConstantHandle = default(LocalConstantHandle); var encoder = new MethodBodyStreamEncoder(ilBuilder); var mvidStringHandle = default(UserStringHandle); mvidStringFixup = default(Blob); int methodRid = 1; foreach (IMethodDefinition method in methods) { _cancellationToken.ThrowIfCancellationRequested(); int bodyOffset; IMethodBody body; StandaloneSignatureHandle localSignatureHandleOpt; if (method.HasBody()) { body = method.GetBody(Context); if (body != null) { localSignatureHandleOpt = this.SerializeLocalVariablesSignature(body); // TODO: consider parallelizing these (local signature tokens can be piped into IL serialization & debug info generation) bodyOffset = SerializeMethodBody(encoder, body, localSignatureHandleOpt, ref mvidStringHandle, ref mvidStringFixup); nativePdbWriterOpt?.SerializeDebugInfo(body, localSignatureHandleOpt, customDebugInfoWriter); } else { bodyOffset = 0; localSignatureHandleOpt = default(StandaloneSignatureHandle); } } else { // 0 is actually written to metadata when the row is serialized bodyOffset = -1; body = null; localSignatureHandleOpt = default(StandaloneSignatureHandle); } if (_debugMetadataOpt != null) { // methodRid is based on this delta but for async state machine debug info we need the "real" row number // of the method aggregated across generations var aggregateMethodRid = MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(method)); SerializeMethodDebugInfo(body, methodRid, aggregateMethodRid, localSignatureHandleOpt, ref lastLocalVariableHandle, ref lastLocalConstantHandle); } _dynamicAnalysisDataWriterOpt?.SerializeMethodDynamicAnalysisData(body); bodyOffsets[methodRid - 1] = bodyOffset; methodRid++; } return bodyOffsets; } private int SerializeMethodBody(MethodBodyStreamEncoder encoder, IMethodBody methodBody, StandaloneSignatureHandle localSignatureHandleOpt, ref UserStringHandle mvidStringHandle, ref Blob mvidStringFixup) { int ilLength = methodBody.IL.Length; var exceptionRegions = methodBody.ExceptionRegions; bool isSmallBody = ilLength < 64 && methodBody.MaxStack <= 8 && localSignatureHandleOpt.IsNil && exceptionRegions.Length == 0; var smallBodyKey = (methodBody.IL, methodBody.AreLocalsZeroed); // Check if an identical method body has already been serialized. // If so, use the RVA of the already serialized one. // Note that we don't need to rewrite the fake tokens in the body before looking it up. // Don't do small body method caching during deterministic builds until this issue is fixed // https://github.com/dotnet/roslyn/issues/7595 int bodyOffset; if (!_deterministic && isSmallBody && _smallMethodBodies.TryGetValue(smallBodyKey, out bodyOffset)) { return bodyOffset; } var encodedBody = encoder.AddMethodBody( codeSize: methodBody.IL.Length, maxStack: methodBody.MaxStack, exceptionRegionCount: exceptionRegions.Length, hasSmallExceptionRegions: MayUseSmallExceptionHeaders(exceptionRegions), localVariablesSignature: localSignatureHandleOpt, attributes: (methodBody.AreLocalsZeroed ? MethodBodyAttributes.InitLocals : 0), hasDynamicStackAllocation: methodBody.HasStackalloc); // Don't do small body method caching during deterministic builds until this issue is fixed // https://github.com/dotnet/roslyn/issues/7595 if (isSmallBody && !_deterministic) { _smallMethodBodies.Add(smallBodyKey, encodedBody.Offset); } WriteInstructions(encodedBody.Instructions, methodBody.IL, ref mvidStringHandle, ref mvidStringFixup); SerializeMethodBodyExceptionHandlerTable(encodedBody.ExceptionRegions, exceptionRegions); return encodedBody.Offset; } /// <summary> /// Serialize the method local signature to the blob. /// </summary> /// <returns>Standalone signature token</returns> protected virtual StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body) { Debug.Assert(!_tableIndicesAreComplete); var localVariables = body.LocalVariables; if (localVariables.Length == 0) { return default(StandaloneSignatureHandle); } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).LocalVariableSignature(localVariables.Length); foreach (ILocalDefinition local in localVariables) { SerializeLocalVariableType(encoder.AddVariable(), local); } BlobHandle blobIndex = metadata.GetOrAddBlob(builder); var handle = GetOrAddStandaloneSignatureHandle(blobIndex); builder.Free(); return handle; } protected void SerializeLocalVariableType(LocalVariableTypeEncoder encoder, ILocalDefinition local) { if (local.CustomModifiers.Length > 0) { SerializeCustomModifiers(encoder.CustomModifiers(), local.CustomModifiers); } if (module.IsPlatformType(local.Type, PlatformType.SystemTypedReference)) { encoder.TypedReference(); return; } SerializeTypeReference(encoder.Type(local.IsReference, local.IsPinned), local.Type); } internal StandaloneSignatureHandle SerializeLocalConstantStandAloneSignature(ILocalDefinition localConstant) { var builder = PooledBlobBuilder.GetInstance(); var typeEncoder = new BlobEncoder(builder).FieldSignature(); if (localConstant.CustomModifiers.Length > 0) { SerializeCustomModifiers(typeEncoder.CustomModifiers(), localConstant.CustomModifiers); } SerializeTypeReference(typeEncoder, localConstant.Type); BlobHandle blobIndex = metadata.GetOrAddBlob(builder); var signatureHandle = GetOrAddStandaloneSignatureHandle(blobIndex); builder.Free(); return signatureHandle; } private static byte ReadByte(ImmutableArray<byte> buffer, int pos) { return buffer[pos]; } private static int ReadInt32(ImmutableArray<byte> buffer, int pos) { return buffer[pos] | buffer[pos + 1] << 8 | buffer[pos + 2] << 16 | buffer[pos + 3] << 24; } private EntityHandle GetHandle(object reference) { return reference switch { ITypeReference typeReference => GetTypeHandle(typeReference), IFieldReference fieldReference => GetFieldHandle(fieldReference), IMethodReference methodReference => GetMethodHandle(methodReference), ISignature signature => GetStandaloneSignatureHandle(signature), _ => throw ExceptionUtilities.UnexpectedValue(reference) }; } private EntityHandle ResolveEntityHandleFromPseudoToken(int pseudoSymbolToken) { int index = pseudoSymbolToken; var entity = _pseudoSymbolTokenToReferenceMap[index]; if (entity != null) { // EDMAURER since method bodies are not visited as they are in CCI, the operations // that would have been done on them are done here. if (entity is IReference reference) { _referenceVisitor.VisitMethodBodyReference(reference); } else if (entity is ISignature signature) { _referenceVisitor.VisitSignature(signature); } EntityHandle handle = GetHandle(entity); _pseudoSymbolTokenToTokenMap[index] = handle; _pseudoSymbolTokenToReferenceMap[index] = null; // Set to null to bypass next lookup return handle; } return _pseudoSymbolTokenToTokenMap[index]; } private UserStringHandle ResolveUserStringHandleFromPseudoToken(int pseudoStringToken) { int index = pseudoStringToken; var str = _pseudoStringTokenToStringMap[index]; if (str != null) { var handle = GetOrAddUserString(str); _pseudoStringTokenToTokenMap[index] = handle; _pseudoStringTokenToStringMap[index] = null; // Set to null to bypass next lookup return handle; } return _pseudoStringTokenToTokenMap[index]; } private UserStringHandle GetOrAddUserString(string str) { if (!_userStringTokenOverflow) { try { return metadata.GetOrAddUserString(str); } catch (ImageFormatLimitationException) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_TooManyUserStrings, NoLocation.Singleton)); _userStringTokenOverflow = true; } } return default(UserStringHandle); } private ReservedBlob<UserStringHandle> ReserveUserString(int length) { if (!_userStringTokenOverflow) { try { return metadata.ReserveUserString(length); } catch (ImageFormatLimitationException) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_TooManyUserStrings, NoLocation.Singleton)); _userStringTokenOverflow = true; } } return default(ReservedBlob<UserStringHandle>); } internal const uint LiteralMethodDefinitionToken = 0x80000000; internal const uint LiteralGreatestMethodDefinitionToken = 0x40000000; internal const uint SourceDocumentIndex = 0x20000000; internal const uint ModuleVersionIdStringToken = 0x80000000; private void WriteInstructions(Blob finalIL, ImmutableArray<byte> generatedIL, ref UserStringHandle mvidStringHandle, ref Blob mvidStringFixup) { // write the raw body first and then patch tokens: var writer = new BlobWriter(finalIL); writer.WriteBytes(generatedIL); writer.Offset = 0; int offset = 0; while (offset < generatedIL.Length) { var operandType = InstructionOperandTypes.ReadOperandType(generatedIL, ref offset); switch (operandType) { case OperandType.InlineField: case OperandType.InlineMethod: case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineSig: { int pseudoToken = ReadInt32(generatedIL, offset); int token = 0; // If any bits in the high-order byte of the pseudotoken are nonzero, replace the opcode with Ldc_i4 // and either clear the high-order byte in the pseudotoken or ignore the pseudotoken. // This is a trick to enable loading raw metadata token indices as integers. if (operandType == OperandType.InlineTok) { int tokenMask = pseudoToken & unchecked((int)0xff000000); if (tokenMask != 0 && (uint)pseudoToken != 0xffffffff) { Debug.Assert(ReadByte(generatedIL, offset - 1) == (byte)ILOpCode.Ldtoken); writer.Offset = offset - 1; writer.WriteByte((byte)ILOpCode.Ldc_i4); switch ((uint)tokenMask) { case LiteralMethodDefinitionToken: // Crash the compiler if pseudo token fails to resolve to a MethodDefinitionHandle. var handle = (MethodDefinitionHandle)ResolveEntityHandleFromPseudoToken(pseudoToken & 0x00ffffff); token = MetadataTokens.GetToken(handle) & 0x00ffffff; break; case LiteralGreatestMethodDefinitionToken: token = GreatestMethodDefIndex; break; case SourceDocumentIndex: token = _dynamicAnalysisDataWriterOpt.GetOrAddDocument(((CommonPEModuleBuilder)module).GetSourceDocumentFromIndex((uint)(pseudoToken & 0x00ffffff))); break; default: throw ExceptionUtilities.UnexpectedValue(tokenMask); } } } writer.Offset = offset; writer.WriteInt32(token == 0 ? MetadataTokens.GetToken(ResolveEntityHandleFromPseudoToken(pseudoToken)) : token); offset += 4; break; } case OperandType.InlineString: { writer.Offset = offset; int pseudoToken = ReadInt32(generatedIL, offset); UserStringHandle handle; if ((uint)pseudoToken == ModuleVersionIdStringToken) { // The pseudotoken encoding indicates that the string should refer to a textual encoding of the // current module's module version ID (such that the MVID can be realized using Guid.Parse). // The value cannot be determined until very late in the compilation, so reserve a slot for it now and fill in the value later. if (mvidStringHandle.IsNil) { const int guidStringLength = 36; Debug.Assert(guidStringLength == default(Guid).ToString().Length); var reserved = ReserveUserString(guidStringLength); mvidStringHandle = reserved.Handle; mvidStringFixup = reserved.Content; } handle = mvidStringHandle; } else { handle = ResolveUserStringHandleFromPseudoToken(pseudoToken); } writer.WriteInt32(MetadataTokens.GetToken(handle)); offset += 4; break; } case OperandType.InlineBrTarget: case OperandType.InlineI: case OperandType.ShortInlineR: offset += 4; break; case OperandType.InlineSwitch: int argCount = ReadInt32(generatedIL, offset); // skip switch arguments count and arguments offset += (argCount + 1) * 4; break; case OperandType.InlineI8: case OperandType.InlineR: offset += 8; break; case OperandType.InlineNone: break; case OperandType.InlineVar: offset += 2; break; case OperandType.ShortInlineBrTarget: case OperandType.ShortInlineI: case OperandType.ShortInlineVar: offset += 1; break; default: throw ExceptionUtilities.UnexpectedValue(operandType); } } } private void SerializeMethodBodyExceptionHandlerTable(ExceptionRegionEncoder encoder, ImmutableArray<ExceptionHandlerRegion> regions) { foreach (var region in regions) { var exceptionType = region.ExceptionType; encoder.Add( region.HandlerKind, region.TryStartOffset, region.TryLength, region.HandlerStartOffset, region.HandlerLength, (exceptionType != null) ? GetTypeHandle(exceptionType) : default(EntityHandle), region.FilterDecisionStartOffset); } } private static bool MayUseSmallExceptionHeaders(ImmutableArray<ExceptionHandlerRegion> exceptionRegions) { if (!ExceptionRegionEncoder.IsSmallRegionCount(exceptionRegions.Length)) { return false; } foreach (var region in exceptionRegions) { if (!ExceptionRegionEncoder.IsSmallExceptionRegion(region.TryStartOffset, region.TryLength) || !ExceptionRegionEncoder.IsSmallExceptionRegion(region.HandlerStartOffset, region.HandlerLength)) { return false; } } return true; } private void SerializeParameterInformation(ParameterTypeEncoder encoder, IParameterTypeInformation parameterTypeInformation) { var type = parameterTypeInformation.GetType(Context); if (module.IsPlatformType(type, PlatformType.SystemTypedReference)) { Debug.Assert(!parameterTypeInformation.IsByReference); SerializeCustomModifiers(encoder.CustomModifiers(), parameterTypeInformation.CustomModifiers); encoder.TypedReference(); } else { Debug.Assert(parameterTypeInformation.RefCustomModifiers.Length == 0 || parameterTypeInformation.IsByReference); SerializeCustomModifiers(encoder.CustomModifiers(), parameterTypeInformation.RefCustomModifiers); var typeEncoder = encoder.Type(parameterTypeInformation.IsByReference); SerializeCustomModifiers(typeEncoder.CustomModifiers(), parameterTypeInformation.CustomModifiers); SerializeTypeReference(typeEncoder, type); } } private void SerializeFieldSignature(IFieldReference fieldReference, BlobBuilder builder) { var typeEncoder = new BlobEncoder(builder).FieldSignature(); SerializeTypeReference(typeEncoder, fieldReference.GetType(Context)); } private void SerializeMethodSpecificationSignature(BlobBuilder builder, IGenericMethodInstanceReference genericMethodInstanceReference) { var argsEncoder = new BlobEncoder(builder).MethodSpecificationSignature(genericMethodInstanceReference.GetGenericMethod(Context).GenericParameterCount); foreach (ITypeReference genericArgument in genericMethodInstanceReference.GetGenericArguments(Context)) { ITypeReference typeRef = genericArgument; SerializeTypeReference(argsEncoder.AddArgument(), typeRef); } } private void SerializeCustomAttributeSignature(ICustomAttribute customAttribute, BlobBuilder builder) { var parameters = customAttribute.Constructor(Context, reportDiagnostics: false).GetParameters(Context); var arguments = customAttribute.GetArguments(Context); Debug.Assert(parameters.Length == arguments.Length); FixedArgumentsEncoder fixedArgsEncoder; CustomAttributeNamedArgumentsEncoder namedArgsEncoder; new BlobEncoder(builder).CustomAttributeSignature(out fixedArgsEncoder, out namedArgsEncoder); for (int i = 0; i < parameters.Length; i++) { SerializeMetadataExpression(fixedArgsEncoder.AddArgument(), arguments[i], parameters[i].GetType(Context)); } SerializeCustomAttributeNamedArguments(namedArgsEncoder.Count(customAttribute.NamedArgumentCount), customAttribute); } private void SerializeCustomAttributeNamedArguments(NamedArgumentsEncoder encoder, ICustomAttribute customAttribute) { foreach (IMetadataNamedArgument namedArgument in customAttribute.GetNamedArguments(Context)) { NamedArgumentTypeEncoder typeEncoder; NameEncoder nameEncoder; LiteralEncoder literalEncoder; encoder.AddArgument(namedArgument.IsField, out typeEncoder, out nameEncoder, out literalEncoder); SerializeNamedArgumentType(typeEncoder, namedArgument.Type); nameEncoder.Name(namedArgument.ArgumentName); SerializeMetadataExpression(literalEncoder, namedArgument.ArgumentValue, namedArgument.Type); } } private void SerializeNamedArgumentType(NamedArgumentTypeEncoder encoder, ITypeReference type) { if (type is IArrayTypeReference arrayType) { SerializeCustomAttributeArrayType(encoder.SZArray(), arrayType); } else if (module.IsPlatformType(type, PlatformType.SystemObject)) { encoder.Object(); } else { SerializeCustomAttributeElementType(encoder.ScalarType(), type); } } private void SerializeMetadataExpression(LiteralEncoder encoder, IMetadataExpression expression, ITypeReference targetType) { if (expression is MetadataCreateArray a) { ITypeReference targetElementType; VectorEncoder vectorEncoder; if (!(targetType is IArrayTypeReference targetArrayType)) { // implicit conversion from array to object Debug.Assert(this.module.IsPlatformType(targetType, PlatformType.SystemObject)); CustomAttributeArrayTypeEncoder arrayTypeEncoder; encoder.TaggedVector(out arrayTypeEncoder, out vectorEncoder); SerializeCustomAttributeArrayType(arrayTypeEncoder, a.ArrayType); targetElementType = a.ElementType; } else { vectorEncoder = encoder.Vector(); // In FixedArg the element type of the parameter array has to match the element type of the argument array, // but in NamedArg T[] can be assigned to object[]. In that case we need to encode the arguments using // the parameter element type not the argument element type. targetElementType = targetArrayType.GetElementType(this.Context); } var literalsEncoder = vectorEncoder.Count(a.Elements.Length); foreach (IMetadataExpression elemValue in a.Elements) { SerializeMetadataExpression(literalsEncoder.AddLiteral(), elemValue, targetElementType); } } else { ScalarEncoder scalarEncoder; MetadataConstant c = expression as MetadataConstant; if (this.module.IsPlatformType(targetType, PlatformType.SystemObject)) { CustomAttributeElementTypeEncoder typeEncoder; encoder.TaggedScalar(out typeEncoder, out scalarEncoder); // special case null argument assigned to Object parameter - treat as null string if (c != null && c.Value == null && this.module.IsPlatformType(c.Type, PlatformType.SystemObject)) { typeEncoder.String(); } else { SerializeCustomAttributeElementType(typeEncoder, expression.Type); } } else { scalarEncoder = encoder.Scalar(); } if (c != null) { if (c.Type is IArrayTypeReference) { scalarEncoder.NullArray(); return; } Debug.Assert(!module.IsPlatformType(c.Type, PlatformType.SystemType) || c.Value == null); scalarEncoder.Constant(c.Value); } else { scalarEncoder.SystemType(((MetadataTypeOf)expression).TypeToGet.GetSerializedTypeName(Context)); } } } private void SerializeMarshallingDescriptor(IMarshallingInformation marshallingInformation, BlobBuilder writer) { writer.WriteCompressedInteger((int)marshallingInformation.UnmanagedType); switch (marshallingInformation.UnmanagedType) { case UnmanagedType.ByValArray: // NATIVE_TYPE_FIXEDARRAY Debug.Assert(marshallingInformation.NumberOfElements >= 0); writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); if (marshallingInformation.ElementType >= 0) { writer.WriteCompressedInteger((int)marshallingInformation.ElementType); } break; case Constants.UnmanagedType_CustomMarshaler: writer.WriteUInt16(0); // padding object marshaller = marshallingInformation.GetCustomMarshaller(Context); switch (marshaller) { case ITypeReference marshallerTypeRef: this.SerializeTypeName(marshallerTypeRef, writer); break; case null: writer.WriteByte(0); break; default: writer.WriteSerializedString((string)marshaller); break; } var arg = marshallingInformation.CustomMarshallerRuntimeArgument; if (arg != null) { writer.WriteSerializedString(arg); } else { writer.WriteByte(0); } break; case UnmanagedType.LPArray: // NATIVE_TYPE_ARRAY Debug.Assert(marshallingInformation.ElementType >= 0); writer.WriteCompressedInteger((int)marshallingInformation.ElementType); if (marshallingInformation.ParamIndex >= 0) { writer.WriteCompressedInteger(marshallingInformation.ParamIndex); if (marshallingInformation.NumberOfElements >= 0) { writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); writer.WriteByte(1); // The parameter number is valid } } else if (marshallingInformation.NumberOfElements >= 0) { writer.WriteByte(0); // Dummy parameter value emitted so that NumberOfElements can be in a known position writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); writer.WriteByte(0); // The parameter number is not valid } break; case Constants.UnmanagedType_SafeArray: if (marshallingInformation.SafeArrayElementSubtype >= 0) { writer.WriteCompressedInteger((int)marshallingInformation.SafeArrayElementSubtype); var elementType = marshallingInformation.GetSafeArrayElementUserDefinedSubtype(Context); if (elementType != null) { this.SerializeTypeName(elementType, writer); } } break; case UnmanagedType.ByValTStr: // NATIVE_TYPE_FIXEDSYSSTRING writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); break; case UnmanagedType.Interface: case Constants.UnmanagedType_IDispatch: case UnmanagedType.IUnknown: if (marshallingInformation.IidParameterIndex >= 0) { writer.WriteCompressedInteger(marshallingInformation.IidParameterIndex); } break; } } private void SerializeTypeName(ITypeReference typeReference, BlobBuilder writer) { writer.WriteSerializedString(typeReference.GetSerializedTypeName(this.Context)); } /// <summary> /// Computes the string representing the strong name of the given assembly reference. /// </summary> internal static string StrongName(IAssemblyReference assemblyReference) { var identity = assemblyReference.Identity; var pooled = PooledStringBuilder.GetInstance(); StringBuilder sb = pooled.Builder; sb.Append(identity.Name); sb.AppendFormat(CultureInfo.InvariantCulture, ", Version={0}.{1}.{2}.{3}", identity.Version.Major, identity.Version.Minor, identity.Version.Build, identity.Version.Revision); if (!string.IsNullOrEmpty(identity.CultureName)) { sb.AppendFormat(CultureInfo.InvariantCulture, ", Culture={0}", identity.CultureName); } else { sb.Append(", Culture=neutral"); } sb.Append(", PublicKeyToken="); if (identity.PublicKeyToken.Length > 0) { foreach (byte b in identity.PublicKeyToken) { sb.Append(b.ToString("x2")); } } else { sb.Append("null"); } if (identity.IsRetargetable) { sb.Append(", Retargetable=Yes"); } if (identity.ContentType == AssemblyContentType.WindowsRuntime) { sb.Append(", ContentType=WindowsRuntime"); } else { Debug.Assert(identity.ContentType == AssemblyContentType.Default); } return pooled.ToStringAndFree(); } private void SerializePermissionSet(ImmutableArray<ICustomAttribute> permissionSet, BlobBuilder writer) { EmitContext context = this.Context; foreach (ICustomAttribute customAttribute in permissionSet) { bool isAssemblyQualified = true; string typeName = customAttribute.GetType(context).GetSerializedTypeName(context, ref isAssemblyQualified); if (!isAssemblyQualified) { INamespaceTypeReference namespaceType = customAttribute.GetType(context).AsNamespaceTypeReference; if (namespaceType?.GetUnit(context) is IAssemblyReference referencedAssembly) { typeName = typeName + ", " + StrongName(referencedAssembly); } } writer.WriteSerializedString(typeName); var customAttributeArgsBuilder = PooledBlobBuilder.GetInstance(); var namedArgsEncoder = new BlobEncoder(customAttributeArgsBuilder).PermissionSetArguments(customAttribute.NamedArgumentCount); SerializeCustomAttributeNamedArguments(namedArgsEncoder, customAttribute); writer.WriteCompressedInteger(customAttributeArgsBuilder.Count); customAttributeArgsBuilder.WriteContentTo(writer); customAttributeArgsBuilder.Free(); } // TODO: xml for older platforms } private void SerializeReturnValueAndParameters(MethodSignatureEncoder encoder, ISignature signature, ImmutableArray<IParameterTypeInformation> varargParameters) { var declaredParameters = signature.GetParameters(Context); var returnType = signature.GetType(Context); ReturnTypeEncoder returnTypeEncoder; ParametersEncoder parametersEncoder; encoder.Parameters(declaredParameters.Length + varargParameters.Length, out returnTypeEncoder, out parametersEncoder); if (module.IsPlatformType(returnType, PlatformType.SystemTypedReference)) { Debug.Assert(!signature.ReturnValueIsByRef); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); returnTypeEncoder.TypedReference(); } else if (module.IsPlatformType(returnType, PlatformType.SystemVoid)) { Debug.Assert(!signature.ReturnValueIsByRef); Debug.Assert(signature.RefCustomModifiers.IsEmpty); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); returnTypeEncoder.Void(); } else { Debug.Assert(signature.RefCustomModifiers.IsEmpty || signature.ReturnValueIsByRef); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.RefCustomModifiers); var typeEncoder = returnTypeEncoder.Type(signature.ReturnValueIsByRef); SerializeCustomModifiers(typeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); SerializeTypeReference(typeEncoder, returnType); } foreach (IParameterTypeInformation parameter in declaredParameters) { SerializeParameterInformation(parametersEncoder.AddParameter(), parameter); } if (varargParameters.Length > 0) { parametersEncoder = parametersEncoder.StartVarArgs(); foreach (IParameterTypeInformation parameter in varargParameters) { SerializeParameterInformation(parametersEncoder.AddParameter(), parameter); } } } private void SerializeTypeReference(SignatureTypeEncoder encoder, ITypeReference typeReference) { while (true) { // TYPEDREF is only allowed in RetType, Param, LocalVarSig signatures Debug.Assert(!module.IsPlatformType(typeReference, PlatformType.SystemTypedReference)); if (typeReference is IModifiedTypeReference modifiedTypeReference) { SerializeCustomModifiers(encoder.CustomModifiers(), modifiedTypeReference.CustomModifiers); typeReference = modifiedTypeReference.UnmodifiedType; continue; } var primitiveType = typeReference.TypeCode; switch (primitiveType) { case PrimitiveTypeCode.Pointer: case PrimitiveTypeCode.FunctionPointer: case PrimitiveTypeCode.NotPrimitive: break; default: SerializePrimitiveType(encoder, primitiveType); return; } if (typeReference is IPointerTypeReference pointerTypeReference) { typeReference = pointerTypeReference.GetTargetType(Context); encoder = encoder.Pointer(); continue; } if (typeReference is IFunctionPointerTypeReference functionPointerTypeReference) { var signature = functionPointerTypeReference.Signature; var signatureEncoder = encoder.FunctionPointer(convention: signature.CallingConvention.ToSignatureConvention()); SerializeReturnValueAndParameters(signatureEncoder, signature, varargParameters: ImmutableArray<IParameterTypeInformation>.Empty); return; } IGenericTypeParameterReference genericTypeParameterReference = typeReference.AsGenericTypeParameterReference; if (genericTypeParameterReference != null) { encoder.GenericTypeParameter( GetNumberOfInheritedTypeParameters(genericTypeParameterReference.DefiningType) + genericTypeParameterReference.Index); return; } if (typeReference is IArrayTypeReference arrayTypeReference) { typeReference = arrayTypeReference.GetElementType(Context); if (arrayTypeReference.IsSZArray) { encoder = encoder.SZArray(); continue; } else { SignatureTypeEncoder elementType; ArrayShapeEncoder arrayShape; encoder.Array(out elementType, out arrayShape); SerializeTypeReference(elementType, typeReference); arrayShape.Shape(arrayTypeReference.Rank, arrayTypeReference.Sizes, arrayTypeReference.LowerBounds); return; } } if (module.IsPlatformType(typeReference, PlatformType.SystemObject)) { encoder.Object(); return; } IGenericMethodParameterReference genericMethodParameterReference = typeReference.AsGenericMethodParameterReference; if (genericMethodParameterReference != null) { encoder.GenericMethodTypeParameter(genericMethodParameterReference.Index); return; } if (typeReference.IsTypeSpecification()) { ITypeReference uninstantiatedTypeReference = typeReference.GetUninstantiatedGenericType(Context); // Roslyn's uninstantiated type is the same object as the instantiated type for // types closed over their type parameters, so to speak. var consolidatedTypeArguments = ArrayBuilder<ITypeReference>.GetInstance(); typeReference.GetConsolidatedTypeArguments(consolidatedTypeArguments, this.Context); var genericArgsEncoder = encoder.GenericInstantiation( GetTypeHandle(uninstantiatedTypeReference, treatRefAsPotentialTypeSpec: false), consolidatedTypeArguments.Count, typeReference.IsValueType); foreach (ITypeReference typeArgument in consolidatedTypeArguments) { SerializeTypeReference(genericArgsEncoder.AddArgument(), typeArgument); } consolidatedTypeArguments.Free(); return; } encoder.Type(GetTypeHandle(typeReference), typeReference.IsValueType); return; } } private static void SerializePrimitiveType(SignatureTypeEncoder encoder, PrimitiveTypeCode primitiveType) { switch (primitiveType) { case PrimitiveTypeCode.Boolean: encoder.Boolean(); break; case PrimitiveTypeCode.UInt8: encoder.Byte(); break; case PrimitiveTypeCode.Int8: encoder.SByte(); break; case PrimitiveTypeCode.Char: encoder.Char(); break; case PrimitiveTypeCode.Int16: encoder.Int16(); break; case PrimitiveTypeCode.UInt16: encoder.UInt16(); break; case PrimitiveTypeCode.Int32: encoder.Int32(); break; case PrimitiveTypeCode.UInt32: encoder.UInt32(); break; case PrimitiveTypeCode.Int64: encoder.Int64(); break; case PrimitiveTypeCode.UInt64: encoder.UInt64(); break; case PrimitiveTypeCode.Float32: encoder.Single(); break; case PrimitiveTypeCode.Float64: encoder.Double(); break; case PrimitiveTypeCode.IntPtr: encoder.IntPtr(); break; case PrimitiveTypeCode.UIntPtr: encoder.UIntPtr(); break; case PrimitiveTypeCode.String: encoder.String(); break; case PrimitiveTypeCode.Void: // "void" is handled specifically for "void*" with custom modifiers. // If SignatureTypeEncoder supports such cases directly, this can // be removed. See https://github.com/dotnet/corefx/issues/14571. encoder.Builder.WriteByte((byte)System.Reflection.Metadata.PrimitiveTypeCode.Void); break; default: throw ExceptionUtilities.UnexpectedValue(primitiveType); } } private void SerializeCustomAttributeArrayType(CustomAttributeArrayTypeEncoder encoder, IArrayTypeReference arrayTypeReference) { // A single-dimensional, zero-based array is specified as a single byte 0x1D followed by the FieldOrPropType of the element type. // only non-jagged SZ arrays are allowed in attributes // (need to encode the type of the SZ array if the parameter type is Object): Debug.Assert(arrayTypeReference.IsSZArray); var elementType = arrayTypeReference.GetElementType(Context); Debug.Assert(!(elementType is IModifiedTypeReference)); if (module.IsPlatformType(elementType, PlatformType.SystemObject)) { encoder.ObjectArray(); } else { SerializeCustomAttributeElementType(encoder.ElementType(), elementType); } } private void SerializeCustomAttributeElementType(CustomAttributeElementTypeEncoder encoder, ITypeReference typeReference) { // Spec: // The FieldOrPropType shall be exactly one of: // ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_I1, ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_U2, ELEMENT_TYPE_I4, // ELEMENT_TYPE_U4, ELEMENT_TYPE_I8, ELEMENT_TYPE_U8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, ELEMENT_TYPE_STRING. // An enum is specified as a single byte 0x55 followed by a SerString. var primitiveType = typeReference.TypeCode; if (primitiveType != PrimitiveTypeCode.NotPrimitive) { SerializePrimitiveType(encoder, primitiveType); } else if (module.IsPlatformType(typeReference, PlatformType.SystemType)) { encoder.SystemType(); } else { Debug.Assert(typeReference.IsEnum); encoder.Enum(typeReference.GetSerializedTypeName(this.Context)); } } private static void SerializePrimitiveType(CustomAttributeElementTypeEncoder encoder, PrimitiveTypeCode primitiveType) { switch (primitiveType) { case PrimitiveTypeCode.Boolean: encoder.Boolean(); break; case PrimitiveTypeCode.UInt8: encoder.Byte(); break; case PrimitiveTypeCode.Int8: encoder.SByte(); break; case PrimitiveTypeCode.Char: encoder.Char(); break; case PrimitiveTypeCode.Int16: encoder.Int16(); break; case PrimitiveTypeCode.UInt16: encoder.UInt16(); break; case PrimitiveTypeCode.Int32: encoder.Int32(); break; case PrimitiveTypeCode.UInt32: encoder.UInt32(); break; case PrimitiveTypeCode.Int64: encoder.Int64(); break; case PrimitiveTypeCode.UInt64: encoder.UInt64(); break; case PrimitiveTypeCode.Float32: encoder.Single(); break; case PrimitiveTypeCode.Float64: encoder.Double(); break; case PrimitiveTypeCode.String: encoder.String(); break; default: throw ExceptionUtilities.UnexpectedValue(primitiveType); } } private void SerializeCustomModifiers(CustomModifiersEncoder encoder, ImmutableArray<ICustomModifier> modifiers) { foreach (var modifier in modifiers) { encoder = encoder.AddModifier(GetTypeHandle(modifier.GetModifier(Context)), modifier.IsOptional); } } private int GetNumberOfInheritedTypeParameters(ITypeReference type) { INestedTypeReference nestedType = type.AsNestedTypeReference; if (nestedType == null) { return 0; } ISpecializedNestedTypeReference specializedNestedType = nestedType.AsSpecializedNestedTypeReference; if (specializedNestedType != null) { nestedType = specializedNestedType.GetUnspecializedVersion(Context); } int result = 0; type = nestedType.GetContainingType(Context); nestedType = type.AsNestedTypeReference; while (nestedType != null) { result += nestedType.GenericParameterCount; type = nestedType.GetContainingType(Context); nestedType = type.AsNestedTypeReference; } result += type.AsNamespaceTypeReference.GenericParameterCount; return result; } internal static EditAndContinueMethodDebugInformation GetEncMethodDebugInfo(IMethodBody methodBody) { ImmutableArray<LocalSlotDebugInfo> encLocalSlots; // Kickoff method of a state machine (async/iterator method) doesn't have any interesting locals, // so we use its EnC method debug info to store information about locals hoisted to the state machine. var encSlotInfo = methodBody.StateMachineHoistedLocalSlots; if (encSlotInfo.IsDefault) { encLocalSlots = GetLocalSlotDebugInfos(methodBody.LocalVariables); } else { encLocalSlots = GetLocalSlotDebugInfos(encSlotInfo); } return new EditAndContinueMethodDebugInformation(methodBody.MethodId.Ordinal, encLocalSlots, methodBody.ClosureDebugInfo, methodBody.LambdaDebugInfo); } internal static ImmutableArray<LocalSlotDebugInfo> GetLocalSlotDebugInfos(ImmutableArray<ILocalDefinition> locals) { if (!locals.Any(variable => !variable.SlotInfo.Id.IsNone)) { return ImmutableArray<LocalSlotDebugInfo>.Empty; } return locals.SelectAsArray(variable => variable.SlotInfo); } internal static ImmutableArray<LocalSlotDebugInfo> GetLocalSlotDebugInfos(ImmutableArray<EncHoistedLocalInfo> locals) { if (!locals.Any(variable => !variable.SlotInfo.Id.IsNone)) { return ImmutableArray<LocalSlotDebugInfo>.Empty; } return locals.SelectAsArray(variable => variable.SlotInfo); } protected abstract class HeapOrReferenceIndexBase<T> { private readonly MetadataWriter _writer; private readonly List<T> _rows; private readonly int _firstRowId; protected HeapOrReferenceIndexBase(MetadataWriter writer, int lastRowId) { _writer = writer; _rows = new List<T>(); _firstRowId = lastRowId + 1; } public abstract bool TryGetValue(T item, out int index); public int GetOrAdd(T item) { int index; if (!this.TryGetValue(item, out index)) { index = Add(item); } return index; } public IReadOnlyList<T> Rows { get { return _rows; } } public int Add(T item) { Debug.Assert(!_writer._tableIndicesAreComplete); #if DEBUG int i; Debug.Assert(!this.TryGetValue(item, out i)); #endif int index = _firstRowId + _rows.Count; this.AddItem(item, index); _rows.Add(item); return index; } protected abstract void AddItem(T item, int index); } protected sealed class HeapOrReferenceIndex<T> : HeapOrReferenceIndexBase<T> { private readonly Dictionary<T, int> _index; public HeapOrReferenceIndex(MetadataWriter writer, int lastRowId = 0) : this(writer, new Dictionary<T, int>(), lastRowId) { } private HeapOrReferenceIndex(MetadataWriter writer, Dictionary<T, int> index, int lastRowId) : base(writer, lastRowId) { Debug.Assert(index.Count == 0); _index = index; } public override bool TryGetValue(T item, out int index) { return _index.TryGetValue(item, out index); } protected override void AddItem(T item, int index) { _index.Add(item, index); } } protected sealed class TypeReferenceIndex : HeapOrReferenceIndexBase<ITypeReference> { private readonly Dictionary<ITypeReference, int> _index; public TypeReferenceIndex(MetadataWriter writer, int lastRowId = 0) : this(writer, new Dictionary<ITypeReference, int>(ReferenceEqualityComparer.Instance), lastRowId) { } private TypeReferenceIndex(MetadataWriter writer, Dictionary<ITypeReference, int> index, int lastRowId) : base(writer, lastRowId) { Debug.Assert(index.Count == 0); _index = index; } public override bool TryGetValue(ITypeReference item, out int index) { return _index.TryGetValue(item, out index); } protected override void AddItem(ITypeReference item, int index) { _index.Add(item, index); } } protected sealed class InstanceAndStructuralReferenceIndex<T> : HeapOrReferenceIndexBase<T> where T : class, IReference { private readonly Dictionary<T, int> _instanceIndex; private readonly Dictionary<T, int> _structuralIndex; public InstanceAndStructuralReferenceIndex(MetadataWriter writer, IEqualityComparer<T> structuralComparer, int lastRowId = 0) : base(writer, lastRowId) { _instanceIndex = new Dictionary<T, int>(ReferenceEqualityComparer.Instance); _structuralIndex = new Dictionary<T, int>(structuralComparer); } public override bool TryGetValue(T item, out int index) { if (_instanceIndex.TryGetValue(item, out index)) { return true; } if (_structuralIndex.TryGetValue(item, out index)) { _instanceIndex.Add(item, index); return true; } return false; } protected override void AddItem(T item, int index) { _instanceIndex.Add(item, index); _structuralIndex.Add(item, index); } } private class ByteSequenceBoolTupleComparer : IEqualityComparer<(ImmutableArray<byte>, bool)> { internal static readonly ByteSequenceBoolTupleComparer Instance = new ByteSequenceBoolTupleComparer(); private ByteSequenceBoolTupleComparer() { } bool IEqualityComparer<(ImmutableArray<byte>, bool)>.Equals((ImmutableArray<byte>, bool) x, (ImmutableArray<byte>, bool) y) { return x.Item2 == y.Item2 && ByteSequenceComparer.Equals(x.Item1, y.Item1); } int IEqualityComparer<(ImmutableArray<byte>, bool)>.GetHashCode((ImmutableArray<byte>, bool) x) { return Hash.Combine(ByteSequenceComparer.GetHashCode(x.Item1), x.Item2.GetHashCode()); } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/VisualBasic/Portable/Semantics/SemanticFacts.vb
' 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. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class Symbol ''' <summary> ''' Determine if two methods have the same signature according to section 4.1.1 of the VB language spec. ''' The name, number of type parameters, and number and types of the method's non-optional parameters are ''' considered. ByRef/Byval, parameter names, returns type, constraints, or optional parameters are not considered. ''' </summary> Friend Shared Function HaveSameSignature(method1 As MethodSymbol, method2 As MethodSymbol) As Boolean Dim comparisonResults As SymbolComparisonResults = MethodSignatureComparer.DetailedCompare( method1, method2, SymbolComparisonResults.AllMismatches And Not SymbolComparisonResults.MismatchesForConflictingMethods) Return comparisonResults = 0 End Function Friend Shared Function HaveSameSignatureAndConstraintsAndReturnType(method1 As MethodSymbol, method2 As MethodSymbol) As Boolean Return MethodSignatureComparer.VisualBasicSignatureAndConstraintsAndReturnTypeComparer.Equals(method1, method2) End Function ''' <summary> ''' Checks if <paramref name="symbol"/> is accessible from within type <paramref name="within"/>. ''' </summary> ''' <param name="symbol">The symbol for the accessibility check.</param> ''' <param name="within">The type to use as a context for the check.</param> ''' <param name="throughTypeOpt"> ''' The type of an expression that <paramref name="symbol"/> is accessed off of, if any. ''' This is needed to properly check accessibility of protected members. ''' </param> ''' <returns></returns> Public Shared Function IsSymbolAccessible(symbol As Symbol, within As NamedTypeSymbol, Optional throughTypeOpt As NamedTypeSymbol = Nothing) As Boolean If symbol Is Nothing Then Throw New ArgumentNullException(NameOf(symbol)) End If If within Is Nothing Then Throw New ArgumentNullException(NameOf(within)) End If Return AccessCheck.IsSymbolAccessible(symbol, within, throughTypeOpt, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) End Function ''' <summary> ''' Checks if <paramref name="symbol"/> is accessible from within the assembly <paramref name="within"/>', but outside any ''' type. Protected members are deemed inaccessible. ''' </summary> ''' <param name="symbol">The symbol to check accessibility.</param> ''' <param name="within">The assembly to check accessibility within.</param> ''' <returns>True if symbol is accessible. False otherwise.</returns> Public Shared Function IsSymbolAccessible(symbol As Symbol, within As AssemblySymbol) As Boolean If symbol Is Nothing Then Throw New ArgumentNullException(NameOf(symbol)) End If If within Is Nothing Then Throw New ArgumentNullException(NameOf(within)) End If Return AccessCheck.IsSymbolAccessible(symbol, within, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) End Function End Class End Namespace
' 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. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class Symbol ''' <summary> ''' Determine if two methods have the same signature according to section 4.1.1 of the VB language spec. ''' The name, number of type parameters, and number and types of the method's non-optional parameters are ''' considered. ByRef/Byval, parameter names, returns type, constraints, or optional parameters are not considered. ''' </summary> Friend Shared Function HaveSameSignature(method1 As MethodSymbol, method2 As MethodSymbol) As Boolean Dim comparisonResults As SymbolComparisonResults = MethodSignatureComparer.DetailedCompare( method1, method2, SymbolComparisonResults.AllMismatches And Not SymbolComparisonResults.MismatchesForConflictingMethods) Return comparisonResults = 0 End Function Friend Shared Function HaveSameSignatureAndConstraintsAndReturnType(method1 As MethodSymbol, method2 As MethodSymbol) As Boolean Return MethodSignatureComparer.VisualBasicSignatureAndConstraintsAndReturnTypeComparer.Equals(method1, method2) End Function ''' <summary> ''' Checks if <paramref name="symbol"/> is accessible from within type <paramref name="within"/>. ''' </summary> ''' <param name="symbol">The symbol for the accessibility check.</param> ''' <param name="within">The type to use as a context for the check.</param> ''' <param name="throughTypeOpt"> ''' The type of an expression that <paramref name="symbol"/> is accessed off of, if any. ''' This is needed to properly check accessibility of protected members. ''' </param> ''' <returns></returns> Public Shared Function IsSymbolAccessible(symbol As Symbol, within As NamedTypeSymbol, Optional throughTypeOpt As NamedTypeSymbol = Nothing) As Boolean If symbol Is Nothing Then Throw New ArgumentNullException(NameOf(symbol)) End If If within Is Nothing Then Throw New ArgumentNullException(NameOf(within)) End If Return AccessCheck.IsSymbolAccessible(symbol, within, throughTypeOpt, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) End Function ''' <summary> ''' Checks if <paramref name="symbol"/> is accessible from within the assembly <paramref name="within"/>', but outside any ''' type. Protected members are deemed inaccessible. ''' </summary> ''' <param name="symbol">The symbol to check accessibility.</param> ''' <param name="within">The assembly to check accessibility within.</param> ''' <returns>True if symbol is accessible. False otherwise.</returns> Public Shared Function IsSymbolAccessible(symbol As Symbol, within As AssemblySymbol) As Boolean If symbol Is Nothing Then Throw New ArgumentNullException(NameOf(symbol)) End If If within Is Nothing Then Throw New ArgumentNullException(NameOf(within)) End If Return AccessCheck.IsSymbolAccessible(symbol, within, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) End Function End Class End Namespace
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IInvocationOperation.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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IInvocationOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IInvocation_StaticMethodWithInstanceReceiver() { string source = @" class C { static void M1() { } public static void M2() { var c = new C(); /*<bind>*/c.M1()/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'c.M1()') Children(1): ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(9,19): error CS0176: Member 'C.M1()' cannot be accessed with an instance reference; qualify it with a type name instead // /*<bind>*/c.M1()/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.M1").WithArguments("C.M1()").WithLocation(9, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IInvocation_StaticMethodAccessOnType() { string source = @" class C { static void M1() { } public static void M2() { /*<bind>*/C.M1()/*</bind>*/; } } "; string expectedOperationTree = @" IInvocationOperation (void C.M1()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C.M1()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IInvocation_InstanceMethodAccessOnType() { string source = @" class C { void M1() { } public static void M2() { /*<bind>*/C.M1()/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'C.M1()') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'C') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.M1()' // /*<bind>*/C.M1()/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.M1").WithArguments("C.M1()").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_01() { string source = @" public class MyClass { void M(bool b, object o1, object o2, object o3, object o4) /*<bind>*/{ M2(o1, o2, b ? o3 : o4); }/*</bind>*/ void M2(object o1, object o2, object o3) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass, IsImplicit) (Syntax: 'M2') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(o1, o2, b ? o3 : o4);') Expression: IInvocationOperation ( void MyClass.M2(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(o1, o2, b ? o3 : o4)') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'M2') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o2') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'b ? o3 : o4') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o3 : o4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_02() { string source = @" public class MyClass { void M(bool b, object o1, object o2, object o3, object o4) /*<bind>*/{ M2(o1, o2, b ? o3 : o4); }/*</bind>*/ static void M2(object o1, object o2, object o3) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(o1, o2, b ? o3 : o4);') Expression: IInvocationOperation (void MyClass.M2(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(o1, o2, b ? o3 : o4)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o2') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'b ? o3 : o4') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o3 : o4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_03() { string source = @" public class MyClass { void M(bool b, object o1, object o2) /*<bind>*/{ (b ? o1 : o2).ToString(); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(b ? o1 : o ... ToString();') Expression: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '(b ? o1 : o2).ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o1 : o2') Arguments(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_04() { string source = @" public class MyClass { void M(bool b, object o1, object o2, object o3, object o4) /*<bind>*/{ M2(o2: o3, o3: o4, o1: b ? o1 : o2); }/*</bind>*/ void M2(object o1, object o2, object o3) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass, IsImplicit) (Syntax: 'M2') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(o2: o3, ... ? o1 : o2);') Expression: IInvocationOperation ( void MyClass.M2(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'M2') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o2: o3') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'o3: o4') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1: b ? o1 : o2') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o1 : o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_05() { string source = @" public class MyClass { void M(bool b, object o1, object o2, object o3, object o4) /*<bind>*/{ M2(o2: o3, o1: b ? o1 : o2); }/*</bind>*/ void M2(object o1, object o2, object o3 = null) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass, IsImplicit) (Syntax: 'M2') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(o2: o3, ... ? o1 : o2);') Expression: IInvocationOperation ( void MyClass.M2(System.Object o1, System.Object o2, [System.Object o3 = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'M2') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o2: o3') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1: b ? o1 : o2') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o1 : o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: o3) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_06() { string source = @" public class MyClass { void M(MyClass c1, MyClass c2, object o1, object o2) /*<bind>*/{ c1.M2(o1); (c1 ?? c2).M2(o2); }/*</bind>*/ static void M2(object o1) { } } "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,9): error CS0176: Member 'MyClass.M2(object)' cannot be accessed with an instance reference; qualify it with a type name instead // c1.M2(o1); Diagnostic(ErrorCode.ERR_ObjectProhibited, "c1.M2").WithArguments("MyClass.M2(object)").WithLocation(6, 9), // file.cs(7,9): error CS0176: Member 'MyClass.M2(object)' cannot be accessed with an instance reference; qualify it with a type name instead // (c1 ?? c2).M2(o2); Diagnostic(ErrorCode.ERR_ObjectProhibited, "(c1 ?? c2).M2").WithArguments("MyClass.M2(object)").WithLocation(7, 9) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c1.M2(o1);') Expression: IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'c1.M2(o1)') Children(2): IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: MyClass, IsInvalid) (Syntax: 'c1') IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B2] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: MyClass, IsInvalid) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsInvalid, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsInvalid, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: MyClass, IsInvalid) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '(c1 ?? c2).M2(o2);') Expression: IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: '(c1 ?? c2).M2(o2)') Children(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsInvalid, IsImplicit) (Syntax: 'c1 ?? c2') IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_07() { string source = @" public class MyClass { void M(object o1, object o2, object o3, object o4, object o5) /*<bind>*/{ M1(o1, M2(o2 ?? o3), o4 ?? o5); }/*</bind>*/ static void M1(object o1, object o2, object o3) { } static object M2(object o1) { throw null; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [3] [5] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o2') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(o2 ?? o3)') Value: IInvocationOperation (System.Object MyClass.M2(System.Object o1)) (OperationKind.Invocation, Type: System.Object) (Syntax: 'M2(o2 ?? o3)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o2 ?? o3') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2 ?? o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R2} Entering: {R4} } .locals {R4} { CaptureIds: [4] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o4') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Leaving: {R4} Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Next (Regular) Block[B9] Leaving: {R4} } Block[B8] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o5') Value: IParameterReferenceOperation: o5 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o5') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1(o1, M2(o ... o4 ?? o5);') Expression: IInvocationOperation (void MyClass.M1(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1(o1, M2(o ... , o4 ?? o5)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'M2(o2 ?? o3)') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'M2(o2 ?? o3)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'o4 ?? o5') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4 ?? o5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B10] Leaving: {R1} } Block[B10] - Exit Predecessors: [B9] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_08() { string source = @" public class MyClass { void M(object o2, object o3, object o4) /*<bind>*/{ M1(M2(o2 ?? o3), o4); }/*</bind>*/ static void M1(object o1, object o2) { } static object M2(object o1) { throw null; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o2') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1(M2(o2 ?? o3), o4);') Expression: IInvocationOperation (void MyClass.M1(System.Object o1, System.Object o2)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1(M2(o2 ?? o3), o4)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'M2(o2 ?? o3)') IInvocationOperation (System.Object MyClass.M2(System.Object o1)) (OperationKind.Invocation, Type: System.Object) (Syntax: 'M2(o2 ?? o3)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o2 ?? o3') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2 ?? o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o4') IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_09() { string source = @" public class MyClass { void M(object o2, object o3, object o4, object o5) /*<bind>*/{ M1(M2(o2 ?? o3), o4 ?? o5); }/*</bind>*/ static void M1(object o1, object o2) { } static object M2(object o1) { throw null; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { CaptureIds: [2] [4] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o2') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(o2 ?? o3)') Value: IInvocationOperation (System.Object MyClass.M2(System.Object o1)) (OperationKind.Invocation, Type: System.Object) (Syntax: 'M2(o2 ?? o3)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o2 ?? o3') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2 ?? o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R2} Entering: {R4} } .locals {R4} { CaptureIds: [3] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o4') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Leaving: {R4} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Next (Regular) Block[B8] Leaving: {R4} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o5') Value: IParameterReferenceOperation: o5 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o5') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1(M2(o2 ?? ... o4 ?? o5);') Expression: IInvocationOperation (void MyClass.M1(System.Object o1, System.Object o2)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1(M2(o2 ?? ... , o4 ?? o5)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'M2(o2 ?? o3)') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'M2(o2 ?? o3)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o4 ?? o5') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4 ?? o5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_10() { string source = @" public class MyClass { void M(object o1, object o2, object o3, object o4, object o5) /*<bind>*/{ M1(o1 ?? o2, o3, o4 ?? o5); }/*</bind>*/ static void M1(object o1, object o2, object o3) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] [2] [4] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o4') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o5') Value: IParameterReferenceOperation: o5 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o5') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1(o1 ?? o2 ... o4 ?? o5);') Expression: IInvocationOperation (void MyClass.M1(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1(o1 ?? o2 ... , o4 ?? o5)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1 ?? o2') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1 ?? o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o3') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'o4 ?? o5') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4 ?? o5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_11() { string source = @" public class MyClass { void M(bool b, object o1, object o2, object o3, object o4, object o5) /*<bind>*/{ M1(b ? o1 : o2, o3, o4 ?? o5); }/*</bind>*/ static void M1(object o1, object o2, object o3) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B5] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o4') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Leaving: {R2} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Next (Regular) Block[B8] Leaving: {R2} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o5') Value: IParameterReferenceOperation: o5 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o5') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1(b ? o1 : ... o4 ?? o5);') Expression: IInvocationOperation (void MyClass.M1(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1(b ? o1 : ... , o4 ?? o5)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'b ? o1 : o2') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o1 : o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o3') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'o4 ?? o5') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4 ?? o5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// 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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IInvocationOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IInvocation_StaticMethodWithInstanceReceiver() { string source = @" class C { static void M1() { } public static void M2() { var c = new C(); /*<bind>*/c.M1()/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'c.M1()') Children(1): ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(9,19): error CS0176: Member 'C.M1()' cannot be accessed with an instance reference; qualify it with a type name instead // /*<bind>*/c.M1()/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectProhibited, "c.M1").WithArguments("C.M1()").WithLocation(9, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IInvocation_StaticMethodAccessOnType() { string source = @" class C { static void M1() { } public static void M2() { /*<bind>*/C.M1()/*</bind>*/; } } "; string expectedOperationTree = @" IInvocationOperation (void C.M1()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'C.M1()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IInvocation_InstanceMethodAccessOnType() { string source = @" class C { void M1() { } public static void M2() { /*<bind>*/C.M1()/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'C.M1()') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'C') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,19): error CS0120: An object reference is required for the non-static field, method, or property 'C.M1()' // /*<bind>*/C.M1()/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectRequired, "C.M1").WithArguments("C.M1()").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_01() { string source = @" public class MyClass { void M(bool b, object o1, object o2, object o3, object o4) /*<bind>*/{ M2(o1, o2, b ? o3 : o4); }/*</bind>*/ void M2(object o1, object o2, object o3) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass, IsImplicit) (Syntax: 'M2') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(o1, o2, b ? o3 : o4);') Expression: IInvocationOperation ( void MyClass.M2(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(o1, o2, b ? o3 : o4)') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'M2') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o2') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'b ? o3 : o4') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o3 : o4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_02() { string source = @" public class MyClass { void M(bool b, object o1, object o2, object o3, object o4) /*<bind>*/{ M2(o1, o2, b ? o3 : o4); }/*</bind>*/ static void M2(object o1, object o2, object o3) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(o1, o2, b ? o3 : o4);') Expression: IInvocationOperation (void MyClass.M2(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(o1, o2, b ? o3 : o4)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o2') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'b ? o3 : o4') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o3 : o4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_03() { string source = @" public class MyClass { void M(bool b, object o1, object o2) /*<bind>*/{ (b ? o1 : o2).ToString(); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(b ? o1 : o ... ToString();') Expression: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '(b ? o1 : o2).ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o1 : o2') Arguments(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_04() { string source = @" public class MyClass { void M(bool b, object o1, object o2, object o3, object o4) /*<bind>*/{ M2(o2: o3, o3: o4, o1: b ? o1 : o2); }/*</bind>*/ void M2(object o1, object o2, object o3) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass, IsImplicit) (Syntax: 'M2') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(o2: o3, ... ? o1 : o2);') Expression: IInvocationOperation ( void MyClass.M2(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'M2') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o2: o3') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'o3: o4') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1: b ? o1 : o2') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o1 : o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_05() { string source = @" public class MyClass { void M(bool b, object o1, object o2, object o3, object o4) /*<bind>*/{ M2(o2: o3, o1: b ? o1 : o2); }/*</bind>*/ void M2(object o1, object o2, object o3 = null) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass, IsImplicit) (Syntax: 'M2') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(o2: o3, ... ? o1 : o2);') Expression: IInvocationOperation ( void MyClass.M2(System.Object o1, System.Object o2, [System.Object o3 = null])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'M2') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o2: o3') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1: b ? o1 : o2') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o1 : o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: o3) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'M2(o2: o3, ... ? o1 : o2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_06() { string source = @" public class MyClass { void M(MyClass c1, MyClass c2, object o1, object o2) /*<bind>*/{ c1.M2(o1); (c1 ?? c2).M2(o2); }/*</bind>*/ static void M2(object o1) { } } "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,9): error CS0176: Member 'MyClass.M2(object)' cannot be accessed with an instance reference; qualify it with a type name instead // c1.M2(o1); Diagnostic(ErrorCode.ERR_ObjectProhibited, "c1.M2").WithArguments("MyClass.M2(object)").WithLocation(6, 9), // file.cs(7,9): error CS0176: Member 'MyClass.M2(object)' cannot be accessed with an instance reference; qualify it with a type name instead // (c1 ?? c2).M2(o2); Diagnostic(ErrorCode.ERR_ObjectProhibited, "(c1 ?? c2).M2").WithArguments("MyClass.M2(object)").WithLocation(7, 9) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c1.M2(o1);') Expression: IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'c1.M2(o1)') Children(2): IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: MyClass, IsInvalid) (Syntax: 'c1') IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B2] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: MyClass, IsInvalid) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsInvalid, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsInvalid, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: MyClass, IsInvalid) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '(c1 ?? c2).M2(o2);') Expression: IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: '(c1 ?? c2).M2(o2)') Children(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsInvalid, IsImplicit) (Syntax: 'c1 ?? c2') IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_07() { string source = @" public class MyClass { void M(object o1, object o2, object o3, object o4, object o5) /*<bind>*/{ M1(o1, M2(o2 ?? o3), o4 ?? o5); }/*</bind>*/ static void M1(object o1, object o2, object o3) { } static object M2(object o1) { throw null; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [3] [5] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o2') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(o2 ?? o3)') Value: IInvocationOperation (System.Object MyClass.M2(System.Object o1)) (OperationKind.Invocation, Type: System.Object) (Syntax: 'M2(o2 ?? o3)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o2 ?? o3') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2 ?? o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R2} Entering: {R4} } .locals {R4} { CaptureIds: [4] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Jump if True (Regular) to Block[B8] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o4') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Leaving: {R4} Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Next (Regular) Block[B9] Leaving: {R4} } Block[B8] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o5') Value: IParameterReferenceOperation: o5 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o5') Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B7] [B8] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1(o1, M2(o ... o4 ?? o5);') Expression: IInvocationOperation (void MyClass.M1(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1(o1, M2(o ... , o4 ?? o5)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'M2(o2 ?? o3)') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'M2(o2 ?? o3)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'o4 ?? o5') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4 ?? o5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B10] Leaving: {R1} } Block[B10] - Exit Predecessors: [B9] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_08() { string source = @" public class MyClass { void M(object o2, object o3, object o4) /*<bind>*/{ M1(M2(o2 ?? o3), o4); }/*</bind>*/ static void M1(object o1, object o2) { } static object M2(object o1) { throw null; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o2') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1(M2(o2 ?? o3), o4);') Expression: IInvocationOperation (void MyClass.M1(System.Object o1, System.Object o2)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1(M2(o2 ?? o3), o4)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'M2(o2 ?? o3)') IInvocationOperation (System.Object MyClass.M2(System.Object o1)) (OperationKind.Invocation, Type: System.Object) (Syntax: 'M2(o2 ?? o3)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o2 ?? o3') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2 ?? o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o4') IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_09() { string source = @" public class MyClass { void M(object o2, object o3, object o4, object o5) /*<bind>*/{ M1(M2(o2 ?? o3), o4 ?? o5); }/*</bind>*/ static void M1(object o1, object o2) { } static object M2(object o1) { throw null; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} {R3} .locals {R1} { CaptureIds: [2] [4] .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o2') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Leaving: {R3} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2') Next (Regular) Block[B4] Leaving: {R3} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2(o2 ?? o3)') Value: IInvocationOperation (System.Object MyClass.M2(System.Object o1)) (OperationKind.Invocation, Type: System.Object) (Syntax: 'M2(o2 ?? o3)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o2 ?? o3') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o2 ?? o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B5] Leaving: {R2} Entering: {R4} } .locals {R4} { CaptureIds: [3] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o4') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Leaving: {R4} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Next (Regular) Block[B8] Leaving: {R4} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o5') Value: IParameterReferenceOperation: o5 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o5') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1(M2(o2 ?? ... o4 ?? o5);') Expression: IInvocationOperation (void MyClass.M1(System.Object o1, System.Object o2)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1(M2(o2 ?? ... , o4 ?? o5)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'M2(o2 ?? o3)') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'M2(o2 ?? o3)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o4 ?? o5') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4 ?? o5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_10() { string source = @" public class MyClass { void M(object o1, object o2, object o3, object o4, object o5) /*<bind>*/{ M1(o1 ?? o2, o3, o4 ?? o5); }/*</bind>*/ static void M1(object o1, object o2, object o3) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] [2] [4] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o4') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o5') Value: IParameterReferenceOperation: o5 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o5') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1(o1 ?? o2 ... o4 ?? o5);') Expression: IInvocationOperation (void MyClass.M1(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1(o1 ?? o2 ... , o4 ?? o5)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'o1 ?? o2') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o1 ?? o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o3') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'o4 ?? o5') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4 ?? o5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvocationFlow_11() { string source = @" public class MyClass { void M(bool b, object o1, object o2, object o3, object o4, object o5) /*<bind>*/{ M1(b ? o1 : o2, o3, o4 ?? o5); }/*</bind>*/ static void M1(object o1, object o2, object o3) { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o1') Value: IParameterReferenceOperation: o1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o2') Value: IParameterReferenceOperation: o2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o3') Value: IParameterReferenceOperation: o3 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o3') Next (Regular) Block[B5] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IParameterReferenceOperation: o4 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o4') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'o4') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Leaving: {R2} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o4') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4') Next (Regular) Block[B8] Leaving: {R2} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'o5') Value: IParameterReferenceOperation: o5 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o5') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M1(b ? o1 : ... o4 ?? o5);') Expression: IInvocationOperation (void MyClass.M1(System.Object o1, System.Object o2, System.Object o3)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M1(b ? o1 : ... , o4 ?? o5)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o1) (OperationKind.Argument, Type: null) (Syntax: 'b ? o1 : o2') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'b ? o1 : o2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o2) (OperationKind.Argument, Type: null) (Syntax: 'o3') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: o3) (OperationKind.Argument, Type: null) (Syntax: 'o4 ?? o5') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'o4 ?? o5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/CodeAnalysisTest/PEWriter/UsedNamespaceOrTypeTests.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.Reflection.Metadata; using Microsoft.Cci; using Microsoft.CodeAnalysis.Emit; using Moq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.PEWriter { public sealed class UsedNamespaceOrTypeTests { public class EqualsProxy { public readonly string Name; public EqualsProxy(string name) { Name = name; } public override int GetHashCode() => Name.GetHashCode(); public override bool Equals(object obj) => (obj as EqualsProxy)?.Name.Equals(Name) == true; } private static Mock<T> CreateEqualsInterface<T>(string name) where T : class { var mock = new Mock<EqualsProxy>(name) { CallBase = true }; return mock.As<T>(); } private static void RunAll(EqualityUnit<UsedNamespaceOrType> unit) { EqualityUtil.RunAll(unit); } [Fact] public void EqualsTargetTypeSameObject() { var ref1 = CreateEqualsInterface<ITypeReference>("ref1"); var ref2 = CreateEqualsInterface<ITypeReference>("ref2"); var value = UsedNamespaceOrType.CreateType(ref1.Object, "alias"); var unit = EqualityUnit .Create(value) .WithEqualValues( value, UsedNamespaceOrType.CreateType(ref1.Object, "alias")) .WithNotEqualValues( UsedNamespaceOrType.CreateNamespace(new Mock<INamespace>(MockBehavior.Strict).Object), UsedNamespaceOrType.CreateType(ref2.Object, "alias"), UsedNamespaceOrType.CreateType(ref1.Object, "different alias")); RunAll(unit); } [WorkItem(7015, "https://github.com/dotnet/roslyn/issues/7015")] [Fact] public void EqualsTargetTypeSameValue() { var type1 = CreateEqualsInterface<ITypeReference>("type name"); var type2 = CreateEqualsInterface<ITypeReference>("type name"); var type3 = CreateEqualsInterface<ITypeReference>("other type name"); Assert.True(type1.Object.Equals(type2.Object)); Assert.False(type1.Object.Equals(type3.Object)); Assert.True(object.Equals(type1.Object, type2.Object)); var value = UsedNamespaceOrType.CreateType(type1.Object, "alias"); var unit = EqualityUnit .Create(value) .WithEqualValues( value, UsedNamespaceOrType.CreateType(type1.Object, "alias"), UsedNamespaceOrType.CreateType(type2.Object, "alias")) .WithNotEqualValues( UsedNamespaceOrType.CreateType(type1.Object, "different alias"), UsedNamespaceOrType.CreateType(type2.Object, "different alias"), UsedNamespaceOrType.CreateType(type3.Object, "alias"), UsedNamespaceOrType.CreateNamespace(new Mock<INamespace>(MockBehavior.Strict).Object)); RunAll(unit); } [Fact] public void EqualsExternAlias() { var value = UsedNamespaceOrType.CreateExternAlias("alias1"); var unit = EqualityUnit .Create(value) .WithEqualValues( value, UsedNamespaceOrType.CreateExternAlias("alias1")) .WithNotEqualValues(UsedNamespaceOrType.CreateExternAlias("alias2")); RunAll(unit); } [Fact] public void EqualsNamespace() { var ns1 = CreateEqualsInterface<INamespace>("namespace"); var ns2 = CreateEqualsInterface<INamespace>("namespace"); var ns3 = CreateEqualsInterface<INamespace>("other namespace"); var value = UsedNamespaceOrType.CreateNamespace(ns1.Object); var unit = EqualityUnit .Create(value) .WithEqualValues( value, UsedNamespaceOrType.CreateNamespace(ns1.Object), UsedNamespaceOrType.CreateNamespace(ns2.Object)) .WithNotEqualValues( UsedNamespaceOrType.CreateExternAlias("alias"), UsedNamespaceOrType.CreateNamespace(ns1.Object, CreateEqualsInterface<IAssemblyReference>("a").Object), UsedNamespaceOrType.CreateNamespace(ns3.Object)); RunAll(unit); } [Fact] public void EqualsNamespaceAndAssembly() { var assembly1 = CreateEqualsInterface<IAssemblyReference>("assembly"); var assembly2 = CreateEqualsInterface<IAssemblyReference>("assembly"); var assembly3 = CreateEqualsInterface<IAssemblyReference>("other assembly"); var ns1 = CreateEqualsInterface<INamespace>("namespace"); var ns2 = CreateEqualsInterface<INamespace>("namespace"); var ns3 = CreateEqualsInterface<INamespace>("other namespace"); var value = UsedNamespaceOrType.CreateNamespace(ns1.Object, assembly1.Object); var unit = EqualityUnit .Create(value) .WithEqualValues( value, UsedNamespaceOrType.CreateNamespace(ns1.Object, assembly1.Object), UsedNamespaceOrType.CreateNamespace(ns1.Object, assembly2.Object), UsedNamespaceOrType.CreateNamespace(ns2.Object, assembly1.Object)) .WithNotEqualValues( UsedNamespaceOrType.CreateExternAlias("alias"), UsedNamespaceOrType.CreateNamespace(ns1.Object, new Mock<IAssemblyReference>(MockBehavior.Strict).Object), UsedNamespaceOrType.CreateNamespace(ns3.Object)); RunAll(unit); } } }
// 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.Reflection.Metadata; using Microsoft.Cci; using Microsoft.CodeAnalysis.Emit; using Moq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.PEWriter { public sealed class UsedNamespaceOrTypeTests { public class EqualsProxy { public readonly string Name; public EqualsProxy(string name) { Name = name; } public override int GetHashCode() => Name.GetHashCode(); public override bool Equals(object obj) => (obj as EqualsProxy)?.Name.Equals(Name) == true; } private static Mock<T> CreateEqualsInterface<T>(string name) where T : class { var mock = new Mock<EqualsProxy>(name) { CallBase = true }; return mock.As<T>(); } private static void RunAll(EqualityUnit<UsedNamespaceOrType> unit) { EqualityUtil.RunAll(unit); } [Fact] public void EqualsTargetTypeSameObject() { var ref1 = CreateEqualsInterface<ITypeReference>("ref1"); var ref2 = CreateEqualsInterface<ITypeReference>("ref2"); var value = UsedNamespaceOrType.CreateType(ref1.Object, "alias"); var unit = EqualityUnit .Create(value) .WithEqualValues( value, UsedNamespaceOrType.CreateType(ref1.Object, "alias")) .WithNotEqualValues( UsedNamespaceOrType.CreateNamespace(new Mock<INamespace>(MockBehavior.Strict).Object), UsedNamespaceOrType.CreateType(ref2.Object, "alias"), UsedNamespaceOrType.CreateType(ref1.Object, "different alias")); RunAll(unit); } [WorkItem(7015, "https://github.com/dotnet/roslyn/issues/7015")] [Fact] public void EqualsTargetTypeSameValue() { var type1 = CreateEqualsInterface<ITypeReference>("type name"); var type2 = CreateEqualsInterface<ITypeReference>("type name"); var type3 = CreateEqualsInterface<ITypeReference>("other type name"); Assert.True(type1.Object.Equals(type2.Object)); Assert.False(type1.Object.Equals(type3.Object)); Assert.True(object.Equals(type1.Object, type2.Object)); var value = UsedNamespaceOrType.CreateType(type1.Object, "alias"); var unit = EqualityUnit .Create(value) .WithEqualValues( value, UsedNamespaceOrType.CreateType(type1.Object, "alias"), UsedNamespaceOrType.CreateType(type2.Object, "alias")) .WithNotEqualValues( UsedNamespaceOrType.CreateType(type1.Object, "different alias"), UsedNamespaceOrType.CreateType(type2.Object, "different alias"), UsedNamespaceOrType.CreateType(type3.Object, "alias"), UsedNamespaceOrType.CreateNamespace(new Mock<INamespace>(MockBehavior.Strict).Object)); RunAll(unit); } [Fact] public void EqualsExternAlias() { var value = UsedNamespaceOrType.CreateExternAlias("alias1"); var unit = EqualityUnit .Create(value) .WithEqualValues( value, UsedNamespaceOrType.CreateExternAlias("alias1")) .WithNotEqualValues(UsedNamespaceOrType.CreateExternAlias("alias2")); RunAll(unit); } [Fact] public void EqualsNamespace() { var ns1 = CreateEqualsInterface<INamespace>("namespace"); var ns2 = CreateEqualsInterface<INamespace>("namespace"); var ns3 = CreateEqualsInterface<INamespace>("other namespace"); var value = UsedNamespaceOrType.CreateNamespace(ns1.Object); var unit = EqualityUnit .Create(value) .WithEqualValues( value, UsedNamespaceOrType.CreateNamespace(ns1.Object), UsedNamespaceOrType.CreateNamespace(ns2.Object)) .WithNotEqualValues( UsedNamespaceOrType.CreateExternAlias("alias"), UsedNamespaceOrType.CreateNamespace(ns1.Object, CreateEqualsInterface<IAssemblyReference>("a").Object), UsedNamespaceOrType.CreateNamespace(ns3.Object)); RunAll(unit); } [Fact] public void EqualsNamespaceAndAssembly() { var assembly1 = CreateEqualsInterface<IAssemblyReference>("assembly"); var assembly2 = CreateEqualsInterface<IAssemblyReference>("assembly"); var assembly3 = CreateEqualsInterface<IAssemblyReference>("other assembly"); var ns1 = CreateEqualsInterface<INamespace>("namespace"); var ns2 = CreateEqualsInterface<INamespace>("namespace"); var ns3 = CreateEqualsInterface<INamespace>("other namespace"); var value = UsedNamespaceOrType.CreateNamespace(ns1.Object, assembly1.Object); var unit = EqualityUnit .Create(value) .WithEqualValues( value, UsedNamespaceOrType.CreateNamespace(ns1.Object, assembly1.Object), UsedNamespaceOrType.CreateNamespace(ns1.Object, assembly2.Object), UsedNamespaceOrType.CreateNamespace(ns2.Object, assembly1.Object)) .WithNotEqualValues( UsedNamespaceOrType.CreateExternAlias("alias"), UsedNamespaceOrType.CreateNamespace(ns1.Object, new Mock<IAssemblyReference>(MockBehavior.Strict).Object), UsedNamespaceOrType.CreateNamespace(ns3.Object)); RunAll(unit); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/VisualBasic/Portable/Syntax/NamespaceDeclarationSyntaxReference.vb
' 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. Imports System.Threading Imports Microsoft.CodeAnalysis.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' this is a SyntaxReference implementation that lazily translates the result (SyntaxNode) of the original syntax reference ''' to other one. ''' </summary> Friend Class NamespaceDeclarationSyntaxReference Inherits TranslationSyntaxReference Public Sub New(reference As SyntaxReference) MyBase.New(reference) End Sub Protected Overrides Function Translate(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode Dim node = reference.GetSyntax(cancellationToken) ' If the node is a name syntax, it's something like "X" or "X.Y" in : ' Namespace X.Y.Z ' We want to return the full NamespaceStatementSyntax. While TypeOf node Is NameSyntax node = node.Parent End While Debug.Assert(TypeOf node Is CompilationUnitSyntax OrElse TypeOf node Is NamespaceStatementSyntax) Return node End Function End Class End Namespace
' 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. Imports System.Threading Imports Microsoft.CodeAnalysis.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' this is a SyntaxReference implementation that lazily translates the result (SyntaxNode) of the original syntax reference ''' to other one. ''' </summary> Friend Class NamespaceDeclarationSyntaxReference Inherits TranslationSyntaxReference Public Sub New(reference As SyntaxReference) MyBase.New(reference) End Sub Protected Overrides Function Translate(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode Dim node = reference.GetSyntax(cancellationToken) ' If the node is a name syntax, it's something like "X" or "X.Y" in : ' Namespace X.Y.Z ' We want to return the full NamespaceStatementSyntax. While TypeOf node Is NameSyntax node = node.Parent End While Debug.Assert(TypeOf node Is CompilationUnitSyntax OrElse TypeOf node Is NamespaceStatementSyntax) Return node End Function End Class End Namespace
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_PreviousSubmissionReference.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 Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalRewriter { public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { var targetType = (ImplicitNamedTypeSymbol)node.Type; Debug.Assert(targetType.TypeKind == TypeKind.Submission); Debug.Assert(_factory.TopLevelMethod is { IsStatic: false }); Debug.Assert(_factory.CurrentType is { }); Debug.Assert(_previousSubmissionFields != null); var syntax = node.Syntax; var targetScriptReference = _previousSubmissionFields.GetOrMakeField(targetType); var thisReference = new BoundThisReference(syntax, _factory.CurrentType); return new BoundFieldAccess(syntax, thisReference, targetScriptReference, ConstantValue.NotAvailable); } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalRewriter { public override BoundNode VisitPreviousSubmissionReference(BoundPreviousSubmissionReference node) { var targetType = (ImplicitNamedTypeSymbol)node.Type; Debug.Assert(targetType.TypeKind == TypeKind.Submission); Debug.Assert(_factory.TopLevelMethod is { IsStatic: false }); Debug.Assert(_factory.CurrentType is { }); Debug.Assert(_previousSubmissionFields != null); var syntax = node.Syntax; var targetScriptReference = _previousSubmissionFields.GetOrMakeField(targetType); var thisReference = new BoundThisReference(syntax, _factory.CurrentType); return new BoundFieldAccess(syntax, thisReference, targetScriptReference, ConstantValue.NotAvailable); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/EditorFeatures/CSharpTest2/Recommendations/InternalKeywordRecommenderTests.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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class InternalKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(@"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() => await VerifyAbsenceAsync(@"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInternal() => await VerifyAbsenceAsync(@"static internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternalStatic() => await VerifyAbsenceAsync(@"internal static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidInternal() => await VerifyAbsenceAsync(@"virtual internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPrivate() => await VerifyAbsenceAsync(@"private $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedVirtual() { await VerifyKeywordAsync( @"class C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedOverride() { await VerifyKeywordAsync( @"class C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInProperty() { await VerifyKeywordAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAfterAccessor() { await VerifyKeywordAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterInternal() { await VerifyAbsenceAsync( @"class C { int Goo { get; internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAfterProtected() { await VerifyKeywordAsync( @"class C { int Goo { get; protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInIndexer() { await VerifyKeywordAsync( @"class C { int this[int i] { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInIndexerAfterAccessor() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInIndexerAfterInternal() { await VerifyAbsenceAsync( @"class C { int this[int i] { get { } internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInIndexerAfterProtected() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } protected $$"); } } }
// 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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class InternalKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(@"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() => await VerifyAbsenceAsync(@"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInternal() => await VerifyAbsenceAsync(@"static internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternalStatic() => await VerifyAbsenceAsync(@"internal static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidInternal() => await VerifyAbsenceAsync(@"virtual internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPrivate() => await VerifyAbsenceAsync(@"private $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedVirtual() { await VerifyKeywordAsync( @"class C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedOverride() { await VerifyKeywordAsync( @"class C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInProperty() { await VerifyKeywordAsync( @"class C { int Goo { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAfterAccessor() { await VerifyKeywordAsync( @"class C { int Goo { get; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAfterInternal() { await VerifyAbsenceAsync( @"class C { int Goo { get; internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyAfterProtected() { await VerifyKeywordAsync( @"class C { int Goo { get; protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInIndexer() { await VerifyKeywordAsync( @"class C { int this[int i] { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInIndexerAfterAccessor() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInIndexerAfterInternal() { await VerifyAbsenceAsync( @"class C { int this[int i] { get { } internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInIndexerAfterProtected() { await VerifyKeywordAsync( @"class C { int this[int i] { get { } protected $$"); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/TypeInferenceService/AbstractTypeInferenceService.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.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.LanguageServices.TypeInferenceService { internal abstract partial class AbstractTypeInferenceService : ITypeInferenceService { protected abstract AbstractTypeInferrer CreateTypeInferrer(SemanticModel semanticModel, CancellationToken cancellationToken); private static ImmutableArray<ITypeSymbol> InferTypeBasedOnNameIfEmpty( SemanticModel semanticModel, ImmutableArray<ITypeSymbol> result, string nameOpt) { if (result.IsEmpty && nameOpt != null) { return InferTypeBasedOnName(semanticModel, nameOpt); } return result; } private static ImmutableArray<TypeInferenceInfo> InferTypeBasedOnNameIfEmpty( SemanticModel semanticModel, ImmutableArray<TypeInferenceInfo> result, string nameOpt) { if (result.IsEmpty && nameOpt != null) { var types = InferTypeBasedOnName(semanticModel, nameOpt); return types.SelectAsArray(t => new TypeInferenceInfo(t)); } return result; } private static readonly ImmutableArray<string> s_booleanPrefixes = ImmutableArray.Create("Is", "Has", "Contains", "Supports"); private static ImmutableArray<ITypeSymbol> InferTypeBasedOnName( SemanticModel semanticModel, string name) { var matchesBoolean = MatchesBoolean(name); return matchesBoolean ? ImmutableArray.Create<ITypeSymbol>(semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean)) : ImmutableArray<ITypeSymbol>.Empty; } private static bool MatchesBoolean(string name) { foreach (var prefix in s_booleanPrefixes) { if (Matches(name, prefix)) { return true; } } return false; } private static bool Matches(string name, string prefix) { if (name.StartsWith(prefix)) { if (name.Length == prefix.Length) { return true; } var nextChar = name[prefix.Length]; return !char.IsLower(nextChar); } return false; } public ImmutableArray<ITypeSymbol> InferTypes( SemanticModel semanticModel, int position, string nameOpt, CancellationToken cancellationToken) { var result = CreateTypeInferrer(semanticModel, cancellationToken) .InferTypes(position) .Select(t => t.InferredType) .ToImmutableArray(); return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt); } public ImmutableArray<ITypeSymbol> InferTypes( SemanticModel semanticModel, SyntaxNode expression, string nameOpt, CancellationToken cancellationToken) { var result = CreateTypeInferrer(semanticModel, cancellationToken) .InferTypes(expression) .Select(info => info.InferredType) .ToImmutableArray(); return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt); } public ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo( SemanticModel semanticModel, int position, string nameOpt, CancellationToken cancellationToken) { var result = CreateTypeInferrer(semanticModel, cancellationToken).InferTypes(position); return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt); } public ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo( SemanticModel semanticModel, SyntaxNode expression, string nameOpt, CancellationToken cancellationToken) { var result = CreateTypeInferrer(semanticModel, cancellationToken).InferTypes(expression); return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt); } } }
// 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.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.LanguageServices.TypeInferenceService { internal abstract partial class AbstractTypeInferenceService : ITypeInferenceService { protected abstract AbstractTypeInferrer CreateTypeInferrer(SemanticModel semanticModel, CancellationToken cancellationToken); private static ImmutableArray<ITypeSymbol> InferTypeBasedOnNameIfEmpty( SemanticModel semanticModel, ImmutableArray<ITypeSymbol> result, string nameOpt) { if (result.IsEmpty && nameOpt != null) { return InferTypeBasedOnName(semanticModel, nameOpt); } return result; } private static ImmutableArray<TypeInferenceInfo> InferTypeBasedOnNameIfEmpty( SemanticModel semanticModel, ImmutableArray<TypeInferenceInfo> result, string nameOpt) { if (result.IsEmpty && nameOpt != null) { var types = InferTypeBasedOnName(semanticModel, nameOpt); return types.SelectAsArray(t => new TypeInferenceInfo(t)); } return result; } private static readonly ImmutableArray<string> s_booleanPrefixes = ImmutableArray.Create("Is", "Has", "Contains", "Supports"); private static ImmutableArray<ITypeSymbol> InferTypeBasedOnName( SemanticModel semanticModel, string name) { var matchesBoolean = MatchesBoolean(name); return matchesBoolean ? ImmutableArray.Create<ITypeSymbol>(semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean)) : ImmutableArray<ITypeSymbol>.Empty; } private static bool MatchesBoolean(string name) { foreach (var prefix in s_booleanPrefixes) { if (Matches(name, prefix)) { return true; } } return false; } private static bool Matches(string name, string prefix) { if (name.StartsWith(prefix)) { if (name.Length == prefix.Length) { return true; } var nextChar = name[prefix.Length]; return !char.IsLower(nextChar); } return false; } public ImmutableArray<ITypeSymbol> InferTypes( SemanticModel semanticModel, int position, string nameOpt, CancellationToken cancellationToken) { var result = CreateTypeInferrer(semanticModel, cancellationToken) .InferTypes(position) .Select(t => t.InferredType) .ToImmutableArray(); return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt); } public ImmutableArray<ITypeSymbol> InferTypes( SemanticModel semanticModel, SyntaxNode expression, string nameOpt, CancellationToken cancellationToken) { var result = CreateTypeInferrer(semanticModel, cancellationToken) .InferTypes(expression) .Select(info => info.InferredType) .ToImmutableArray(); return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt); } public ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo( SemanticModel semanticModel, int position, string nameOpt, CancellationToken cancellationToken) { var result = CreateTypeInferrer(semanticModel, cancellationToken).InferTypes(position); return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt); } public ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo( SemanticModel semanticModel, SyntaxNode expression, string nameOpt, CancellationToken cancellationToken) { var result = CreateTypeInferrer(semanticModel, cancellationToken).InferTypes(expression); return InferTypeBasedOnNameIfEmpty(semanticModel, result, nameOpt); } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./docs/features/nullable-metadata.md
Nullable Metadata ========= The following describes the representation of nullable annotations in metadata. ## NullableAttribute Type references are annotated in metadata with a `NullableAttribute`. ```C# namespace System.Runtime.CompilerServices { [AttributeUsage( AttributeTargets.Class | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.GenericParameter | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = false, Inherited = false)] public sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte flag) { NullableFlags = new byte[] { flag }; } public NullableAttribute(byte[] flags) { NullableFlags = flags; } } } ``` The `NullableAttribute` type is for compiler use only - it is not permitted in source. The type declaration is synthesized by the compiler if not already included in the compilation. Each type reference in metadata may have an associated `NullableAttribute` with a `byte[]` where each `byte` represents nullability: 0 for oblivious, 1 for not annotated, and 2 for annotated. The `byte[]` is constructed as follows: - Reference type: the nullability (0, 1, or 2), followed by the representation of the type arguments in order including containing types - Nullable value type: the representation of the type argument only - Non-generic value type: skipped - Generic value type: 0, followed by the representation of the type arguments in order including containing types - Array: the nullability (0, 1, or 2), followed by the representation of the element type - Tuple: the representation of the underlying constructed type - Type parameter reference: the nullability (0, 1, or 2, with 0 for unconstrained type parameter) Note that non-generic value types are represented by an empty `byte[]`. However, generic value types and type parameters constrained to value types have an explicit 0 in the `byte[]` for nullability. The reason generic types and type parameters are represented with an explicit `byte` is to simplify metadata import. Specifically, this avoids the need to calculate whether a type parameter is constrained to a value type when decoding nullability metadata, since the constraints may include a (valid) cyclic reference to the type parameter. ### Optimizations If the `byte[]` is empty, the `NullableAttribute` is omitted. If all values in the `byte[]` are the same, the `NullableAttribute` is constructed with that single `byte` value. (For instance, `NullableAttribute(1)` rather than `NullableAttribute(new byte[] { 1, 1 }))`.) ### Type parameters Each type parameter definition may have an associated `NullableAttribute` with a single `byte`: 1. `notnull` constraint: `NullableAttribute(1)` 2. `class` constraint in `#nullable disable` context: `NullableAttribute(0)` 3. `class` constraint in `#nullable enable` context: `NullableAttribute(1)` 4. `class?` constraint: `NullableAttribute(2)` 5. No `notnull`, `class`, `struct`, `unmanaged`, or type constraints in `#nullable disable` context: `NullableAttribute(0)` 6. No `notnull`, `class`, `struct`, `unmanaged`, or type constraints in `#nullable enable` context (equivalent to an `object?` constraint): `NullableAttribute(2)` ## NullableContextAttribute `NullableContextAttribute` can be used to indicate the nullability of type references that have no `NullableAttribute` annotations. ```C# namespace System.Runtime.CompilerServices { [System.AttributeUsage( AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] public sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte flag) { Flag = flag; } } } ``` The `NullableContextAttribute` type is for compiler use only - it is not permitted in source. The type declaration is synthesized by the compiler if not already included in the compilation. The `NullableContextAttribute` is optional - nullable annotations can be represented in metadata with full fidelity using `NullableAttribute` only. `NullableContextAttribute` is valid in metadata on type and method declarations. The `byte` value represents the implicit `NullableAttribute` value for type references within that scope that do not have an explicit `NullableAttribute` and would not otherwise be represented by an empty `byte[]`. The nearest `NullableContextAttribute` in the metadata hierarchy applies. If there are no `NullableContextAttribute` attributes in the hierarchy, missing `NullableAttribute` attributes are treated as `NullableAttribute(0)`. The attribute is not inherited. The C#8 compiler uses the following algorithm to determine which `NullableAttribute` and `NullableContextAttribute` attributes to emit. First, `NullableAttribute` attributes are generated at each type reference and type parameter definition by: calculating the `byte[]`, skipping empty `byte[]`, and collapsing `byte[]` to single `byte` where possible. Then at each level in metadata hierarchy starting at methods: The compiler finds the most common single `byte` value across all the `NullableAttribute` attributes at that level and any `NullableContextAttribute` attributes on immediate children. If there are no single `byte` values, there are no changes. Otherwise, a `NullableContext(value)` attribute is created at that level where `value` is most common value (preferring `0` over `1` and preferring `1` over `2`), and all `NullableAttribute` and `NullableContextAttribute` attributes with that value are removed. Note that an assembly compiled with C#8 where all reference types are oblivious will have no `NullableContextAttribute` and no `NullableAttribute` attributes emitted. That is equivalent to a legacy assembly. ### Examples ```C# // C# representation of metadata [NullableContext(2)] class Program { string s; // string? [Nullable({ 2, 1, 2 }] Dictionary<string, object> d; // Dictionary<string!, object?>? [Nullable(1)] int[] a; // int[]! int[] b; // int[]? [Nullable({ 0, 2 })] object[] c; // object?[]~ } ``` ## Private members To reduce the size of metadata, the C#8 compiler can be configured to not emit attributes for members that are inaccessible outside the assembly (`private` members, and also `internal` members if the assembly does not contain `InternalsVisibleToAttribute` attributes). The compiler behavior is configured from a command-line flag. For now a feature flag is used: `-features:nullablePublicOnly`. If private member attributes are dropped, the compiler will emit a `[module: NullablePublicOnly]` attribute. The presence or absence of the `NullablePublicOnlyAttribute` can be used by tools to interpret the nullability of private members that do not have an associated `NullableAttribute` attribute. For members that do not have explicit accessibility in metadata (specifically for parameters, type parameters, events, and properties), the compiler uses the accessibility of the container to determine whether to emit nullable attributes. ```C# namespace System.Runtime.CompilerServices { [System.AttributeUsage(AttributeTargets.Module, AllowMultiple = false)] public sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool includesInternals) { IncludesInternals = includesInternals; } } } ``` The `NullablePublicOnlyAttribute` type is for compiler use only - it is not permitted in source. The type declaration is synthesized by the compiler if not already included in the compilation. `IncludesInternal` is true if `internal` members are annotated in addition to `public` and `protected` members. ## Compatibility The nullable metadata does not include an explicit version number. Where possible, the compiler will silently ignore attribute forms that are unexpected. The metadata format described here is incompatible with the format used by earlier C#8 previews: 1. Concrete non-generic value types are no longer included in the `byte[]`, and 2. `NullableContextAttribute` attributes are used in place of explicit `NullableAttribute` attributes. Those differences mean that assemblies compiled with earlier previews may be read incorrectly by later previews, and assemblies compiled with later previews may be read incorrectly by earlier previews.
Nullable Metadata ========= The following describes the representation of nullable annotations in metadata. ## NullableAttribute Type references are annotated in metadata with a `NullableAttribute`. ```C# namespace System.Runtime.CompilerServices { [AttributeUsage( AttributeTargets.Class | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.GenericParameter | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = false, Inherited = false)] public sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte flag) { NullableFlags = new byte[] { flag }; } public NullableAttribute(byte[] flags) { NullableFlags = flags; } } } ``` The `NullableAttribute` type is for compiler use only - it is not permitted in source. The type declaration is synthesized by the compiler if not already included in the compilation. Each type reference in metadata may have an associated `NullableAttribute` with a `byte[]` where each `byte` represents nullability: 0 for oblivious, 1 for not annotated, and 2 for annotated. The `byte[]` is constructed as follows: - Reference type: the nullability (0, 1, or 2), followed by the representation of the type arguments in order including containing types - Nullable value type: the representation of the type argument only - Non-generic value type: skipped - Generic value type: 0, followed by the representation of the type arguments in order including containing types - Array: the nullability (0, 1, or 2), followed by the representation of the element type - Tuple: the representation of the underlying constructed type - Type parameter reference: the nullability (0, 1, or 2, with 0 for unconstrained type parameter) Note that non-generic value types are represented by an empty `byte[]`. However, generic value types and type parameters constrained to value types have an explicit 0 in the `byte[]` for nullability. The reason generic types and type parameters are represented with an explicit `byte` is to simplify metadata import. Specifically, this avoids the need to calculate whether a type parameter is constrained to a value type when decoding nullability metadata, since the constraints may include a (valid) cyclic reference to the type parameter. ### Optimizations If the `byte[]` is empty, the `NullableAttribute` is omitted. If all values in the `byte[]` are the same, the `NullableAttribute` is constructed with that single `byte` value. (For instance, `NullableAttribute(1)` rather than `NullableAttribute(new byte[] { 1, 1 }))`.) ### Type parameters Each type parameter definition may have an associated `NullableAttribute` with a single `byte`: 1. `notnull` constraint: `NullableAttribute(1)` 2. `class` constraint in `#nullable disable` context: `NullableAttribute(0)` 3. `class` constraint in `#nullable enable` context: `NullableAttribute(1)` 4. `class?` constraint: `NullableAttribute(2)` 5. No `notnull`, `class`, `struct`, `unmanaged`, or type constraints in `#nullable disable` context: `NullableAttribute(0)` 6. No `notnull`, `class`, `struct`, `unmanaged`, or type constraints in `#nullable enable` context (equivalent to an `object?` constraint): `NullableAttribute(2)` ## NullableContextAttribute `NullableContextAttribute` can be used to indicate the nullability of type references that have no `NullableAttribute` annotations. ```C# namespace System.Runtime.CompilerServices { [System.AttributeUsage( AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] public sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte flag) { Flag = flag; } } } ``` The `NullableContextAttribute` type is for compiler use only - it is not permitted in source. The type declaration is synthesized by the compiler if not already included in the compilation. The `NullableContextAttribute` is optional - nullable annotations can be represented in metadata with full fidelity using `NullableAttribute` only. `NullableContextAttribute` is valid in metadata on type and method declarations. The `byte` value represents the implicit `NullableAttribute` value for type references within that scope that do not have an explicit `NullableAttribute` and would not otherwise be represented by an empty `byte[]`. The nearest `NullableContextAttribute` in the metadata hierarchy applies. If there are no `NullableContextAttribute` attributes in the hierarchy, missing `NullableAttribute` attributes are treated as `NullableAttribute(0)`. The attribute is not inherited. The C#8 compiler uses the following algorithm to determine which `NullableAttribute` and `NullableContextAttribute` attributes to emit. First, `NullableAttribute` attributes are generated at each type reference and type parameter definition by: calculating the `byte[]`, skipping empty `byte[]`, and collapsing `byte[]` to single `byte` where possible. Then at each level in metadata hierarchy starting at methods: The compiler finds the most common single `byte` value across all the `NullableAttribute` attributes at that level and any `NullableContextAttribute` attributes on immediate children. If there are no single `byte` values, there are no changes. Otherwise, a `NullableContext(value)` attribute is created at that level where `value` is most common value (preferring `0` over `1` and preferring `1` over `2`), and all `NullableAttribute` and `NullableContextAttribute` attributes with that value are removed. Note that an assembly compiled with C#8 where all reference types are oblivious will have no `NullableContextAttribute` and no `NullableAttribute` attributes emitted. That is equivalent to a legacy assembly. ### Examples ```C# // C# representation of metadata [NullableContext(2)] class Program { string s; // string? [Nullable({ 2, 1, 2 }] Dictionary<string, object> d; // Dictionary<string!, object?>? [Nullable(1)] int[] a; // int[]! int[] b; // int[]? [Nullable({ 0, 2 })] object[] c; // object?[]~ } ``` ## Private members To reduce the size of metadata, the C#8 compiler can be configured to not emit attributes for members that are inaccessible outside the assembly (`private` members, and also `internal` members if the assembly does not contain `InternalsVisibleToAttribute` attributes). The compiler behavior is configured from a command-line flag. For now a feature flag is used: `-features:nullablePublicOnly`. If private member attributes are dropped, the compiler will emit a `[module: NullablePublicOnly]` attribute. The presence or absence of the `NullablePublicOnlyAttribute` can be used by tools to interpret the nullability of private members that do not have an associated `NullableAttribute` attribute. For members that do not have explicit accessibility in metadata (specifically for parameters, type parameters, events, and properties), the compiler uses the accessibility of the container to determine whether to emit nullable attributes. ```C# namespace System.Runtime.CompilerServices { [System.AttributeUsage(AttributeTargets.Module, AllowMultiple = false)] public sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool includesInternals) { IncludesInternals = includesInternals; } } } ``` The `NullablePublicOnlyAttribute` type is for compiler use only - it is not permitted in source. The type declaration is synthesized by the compiler if not already included in the compilation. `IncludesInternal` is true if `internal` members are annotated in addition to `public` and `protected` members. ## Compatibility The nullable metadata does not include an explicit version number. Where possible, the compiler will silently ignore attribute forms that are unexpected. The metadata format described here is incompatible with the format used by earlier C#8 previews: 1. Concrete non-generic value types are no longer included in the `byte[]`, and 2. `NullableContextAttribute` attributes are used in place of explicit `NullableAttribute` attributes. Those differences mean that assemblies compiled with earlier previews may be read incorrectly by later previews, and assemblies compiled with later previews may be read incorrectly by earlier previews.
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/IdentifierNameSyntax.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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class IdentifierNameSyntax { public override string ToString() { return this.Identifier.Text; } } }
// 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class IdentifierNameSyntax { public override string ToString() { return this.Identifier.Text; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.InProcess.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { internal abstract partial class AbstractNavigateToSearchService { private static ImmutableArray<(PatternMatchKind roslynKind, NavigateToMatchKind vsKind)> s_kindPairs = ImmutableArray.Create( (PatternMatchKind.Exact, NavigateToMatchKind.Exact), (PatternMatchKind.Prefix, NavigateToMatchKind.Prefix), (PatternMatchKind.NonLowercaseSubstring, NavigateToMatchKind.Substring), (PatternMatchKind.StartOfWordSubstring, NavigateToMatchKind.Substring), (PatternMatchKind.CamelCaseExact, NavigateToMatchKind.CamelCaseExact), (PatternMatchKind.CamelCasePrefix, NavigateToMatchKind.CamelCasePrefix), (PatternMatchKind.CamelCaseNonContiguousPrefix, NavigateToMatchKind.CamelCaseNonContiguousPrefix), (PatternMatchKind.CamelCaseSubstring, NavigateToMatchKind.CamelCaseSubstring), (PatternMatchKind.CamelCaseNonContiguousSubstring, NavigateToMatchKind.CamelCaseNonContiguousSubstring), (PatternMatchKind.Fuzzy, NavigateToMatchKind.Fuzzy), // Map our value to 'Fuzzy' as that's the lower value the platform supports. (PatternMatchKind.LowercaseSubstring, NavigateToMatchKind.Fuzzy)); public static Task SearchFullyLoadedProjectInCurrentProcessAsync( Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { return FindSearchResultsAsync( project, priorityDocuments, searchDocument: null, pattern: searchPattern, kinds, onResultFound, cancellationToken); } public static Task SearchFullyLoadedDocumentInCurrentProcessAsync( Document document, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { return FindSearchResultsAsync( document.Project, priorityDocuments: ImmutableArray<Document>.Empty, document, searchPattern, kinds, onResultFound, cancellationToken); } private static async Task FindSearchResultsAsync( Project project, ImmutableArray<Document> priorityDocuments, Document? searchDocument, string pattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { // If the user created a dotted pattern then we'll grab the last part of the name var (patternName, patternContainerOpt) = PatternMatcher.GetNameAndContainer(pattern); var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds); // Prioritize the active documents if we have any. var highPriDocs = priorityDocuments.Where(d => project.ContainsDocument(d.Id)).ToSet(); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, highPriDocs, cancellationToken).ConfigureAwait(false); // Then process non-priority documents. var lowPriDocs = project.Documents.Where(d => !highPriDocs.Contains(d)).ToSet(); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, lowPriDocs, cancellationToken).ConfigureAwait(false); // if the caller is only searching a single doc, and we already covered it above, don't bother computing // source-generator docs. if (searchDocument != null && (highPriDocs.Contains(searchDocument) || lowPriDocs.Contains(searchDocument))) return; // Finally, generate and process and source-generated docs. this may take some time, so we always want to // do this after the other documents. var generatedDocs = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, generatedDocs.ToSet<Document>(), cancellationToken).ConfigureAwait(false); } private static async Task ProcessDocumentsAsync( Document? searchDocument, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, ISet<Document> documents, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var document in documents) { if (searchDocument != null && searchDocument != document) continue; cancellationToken.ThrowIfCancellationRequested(); tasks.Add(Task.Run(() => ProcessDocumentAsync(document, patternName, patternContainer, kinds, onResultFound, cancellationToken), cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static async Task ProcessDocumentAsync( Document document, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { var index = await SyntaxTreeIndex.GetRequiredIndexAsync(document, cancellationToken).ConfigureAwait(false); await ProcessIndexAsync( document.Id, document, patternName, patternContainer, kinds, onResultFound, index, cancellationToken).ConfigureAwait(false); } public static async Task SearchCachedDocumentsInCurrentProcessAsync( HostWorkspaceServices services, ImmutableArray<DocumentKey> documentKeys, ImmutableArray<DocumentKey> priorityDocumentKeys, StorageDatabase database, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onItemFound, CancellationToken cancellationToken) { var stringTable = new StringTable(); var highPriDocsSet = priorityDocumentKeys.ToSet(); var lowPriDocs = documentKeys.WhereAsArray(d => !highPriDocsSet.Contains(d)); // If the user created a dotted pattern then we'll grab the last part of the name var (patternName, patternContainer) = PatternMatcher.GetNameAndContainer(searchPattern); var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds); await SearchCachedDocumentsInCurrentProcessAsync( services, priorityDocumentKeys, database, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false); await SearchCachedDocumentsInCurrentProcessAsync( services, lowPriDocs, database, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false); } private static async Task SearchCachedDocumentsInCurrentProcessAsync( HostWorkspaceServices services, ImmutableArray<DocumentKey> documentKeys, StorageDatabase database, string patternName, string patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onItemFound, StringTable stringTable, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var documentKey in documentKeys) { tasks.Add(Task.Run(async () => { var index = await SyntaxTreeIndex.LoadAsync( services, documentKey, checksum: null, database, stringTable, cancellationToken).ConfigureAwait(false); if (index == null) return; await ProcessIndexAsync( documentKey.Id, document: null, patternName, patternContainer, kinds, onItemFound, index, cancellationToken).ConfigureAwait(false); }, cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static async Task ProcessIndexAsync( DocumentId documentId, Document? document, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, SyntaxTreeIndex index, CancellationToken cancellationToken) { var containerMatcher = patternContainer != null ? PatternMatcher.CreateDotSeparatedContainerMatcher(patternContainer) : null; using var nameMatcher = PatternMatcher.CreatePatternMatcher(patternName, includeMatchedSpans: true, allowFuzzyMatching: true); using var _1 = containerMatcher; foreach (var declaredSymbolInfo in index.DeclaredSymbolInfos) { // Namespaces are never returned in nav-to as they're too common and have too many locations. if (declaredSymbolInfo.Kind == DeclaredSymbolInfoKind.Namespace) continue; await AddResultIfMatchAsync( documentId, document, declaredSymbolInfo, nameMatcher, containerMatcher, kinds, onResultFound, cancellationToken).ConfigureAwait(false); } } private static async Task AddResultIfMatchAsync( DocumentId documentId, Document? document, DeclaredSymbolInfo declaredSymbolInfo, PatternMatcher nameMatcher, PatternMatcher? containerMatcher, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { using var nameMatches = TemporaryArray<PatternMatch>.Empty; using var containerMatches = TemporaryArray<PatternMatch>.Empty; cancellationToken.ThrowIfCancellationRequested(); if (kinds.Contains(declaredSymbolInfo.Kind) && nameMatcher.AddMatches(declaredSymbolInfo.Name, ref nameMatches.AsRef()) && containerMatcher?.AddMatches(declaredSymbolInfo.FullyQualifiedContainerName, ref containerMatches.AsRef()) != false) { // See if we have a match in a linked file. If so, see if we have the same match in // other projects that this file is linked in. If so, include the full set of projects // the match is in so we can display that well in the UI. // // We can only do this in the case where the solution is loaded and thus we can examine // the relationship between this document and the other documents linked to it. In the // case where the solution isn't fully loaded and we're just reading in cached data, we // don't know what other files we're linked to and can't merge results in this fashion. var additionalMatchingProjects = await GetAdditionalProjectsWithMatchAsync( document, declaredSymbolInfo, cancellationToken).ConfigureAwait(false); var result = ConvertResult( documentId, document, declaredSymbolInfo, nameMatches, containerMatches, additionalMatchingProjects); await onResultFound(result).ConfigureAwait(false); } } private static RoslynNavigateToItem ConvertResult( DocumentId documentId, Document? document, DeclaredSymbolInfo declaredSymbolInfo, in TemporaryArray<PatternMatch> nameMatches, in TemporaryArray<PatternMatch> containerMatches, ImmutableArray<ProjectId> additionalMatchingProjects) { var matchKind = GetNavigateToMatchKind(nameMatches); // A match is considered to be case sensitive if all its constituent pattern matches are // case sensitive. var isCaseSensitive = nameMatches.All(m => m.IsCaseSensitive) && containerMatches.All(m => m.IsCaseSensitive); var kind = GetItemKind(declaredSymbolInfo); using var matchedSpans = TemporaryArray<TextSpan>.Empty; foreach (var match in nameMatches) matchedSpans.AddRange(match.MatchedSpans); // If we were not given a Document instance, then we're finding matches in cached data // and thus could be 'stale'. return new RoslynNavigateToItem( isStale: document == null, documentId, additionalMatchingProjects, declaredSymbolInfo, kind, matchKind, isCaseSensitive, matchedSpans.ToImmutableAndClear()); } private static async ValueTask<ImmutableArray<ProjectId>> GetAdditionalProjectsWithMatchAsync( Document? document, DeclaredSymbolInfo declaredSymbolInfo, CancellationToken cancellationToken) { if (document == null) return ImmutableArray<ProjectId>.Empty; using var _ = ArrayBuilder<ProjectId>.GetInstance(out var result); var solution = document.Project.Solution; var linkedDocumentIds = document.GetLinkedDocumentIds(); foreach (var linkedDocumentId in linkedDocumentIds) { var linkedDocument = solution.GetRequiredDocument(linkedDocumentId); var index = await SyntaxTreeIndex.GetRequiredIndexAsync(linkedDocument, cancellationToken).ConfigureAwait(false); // See if the index for the other file also contains this same info. If so, merge the results so the // user only sees them as a single hit in the UI. if (index.DeclaredSymbolInfoSet.Contains(declaredSymbolInfo)) result.Add(linkedDocument.Project.Id); } result.RemoveDuplicates(); return result.ToImmutable(); } private static string GetItemKind(DeclaredSymbolInfo declaredSymbolInfo) { switch (declaredSymbolInfo.Kind) { case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Record: return NavigateToItemKind.Class; case DeclaredSymbolInfoKind.RecordStruct: return NavigateToItemKind.Structure; case DeclaredSymbolInfoKind.Constant: return NavigateToItemKind.Constant; case DeclaredSymbolInfoKind.Delegate: return NavigateToItemKind.Delegate; case DeclaredSymbolInfoKind.Enum: return NavigateToItemKind.Enum; case DeclaredSymbolInfoKind.EnumMember: return NavigateToItemKind.EnumItem; case DeclaredSymbolInfoKind.Event: return NavigateToItemKind.Event; case DeclaredSymbolInfoKind.Field: return NavigateToItemKind.Field; case DeclaredSymbolInfoKind.Interface: return NavigateToItemKind.Interface; case DeclaredSymbolInfoKind.Constructor: case DeclaredSymbolInfoKind.ExtensionMethod: case DeclaredSymbolInfoKind.Method: return NavigateToItemKind.Method; case DeclaredSymbolInfoKind.Module: return NavigateToItemKind.Module; case DeclaredSymbolInfoKind.Indexer: case DeclaredSymbolInfoKind.Property: return NavigateToItemKind.Property; case DeclaredSymbolInfoKind.Struct: return NavigateToItemKind.Structure; default: throw ExceptionUtilities.UnexpectedValue(declaredSymbolInfo.Kind); } } private static NavigateToMatchKind GetNavigateToMatchKind(in TemporaryArray<PatternMatch> nameMatches) { // work backwards through the match kinds. That way our result is as bad as our worst match part. For // example, say the user searches for `Console.Write` and we find `Console.Write` (exact, exact), and // `Console.WriteLine` (exact, prefix). We don't want the latter hit to be considered an `exact` match, and // thus as good as `Console.Write`. for (var i = s_kindPairs.Length - 1; i >= 0; i--) { var (roslynKind, vsKind) = s_kindPairs[i]; foreach (var match in nameMatches) { if (match.Kind == roslynKind) return vsKind; } } return NavigateToMatchKind.Regular; } private readonly struct DeclaredSymbolInfoKindSet { private readonly ImmutableArray<bool> _lookupTable; public DeclaredSymbolInfoKindSet(IEnumerable<string> navigateToItemKinds) { // The 'Contains' method implementation assumes that the DeclaredSymbolInfoKind type is unsigned. Debug.Assert(Enum.GetUnderlyingType(typeof(DeclaredSymbolInfoKind)) == typeof(byte)); var lookupTable = new bool[Enum.GetValues(typeof(DeclaredSymbolInfoKind)).Length]; foreach (var navigateToItemKind in navigateToItemKinds) { switch (navigateToItemKind) { case NavigateToItemKind.Class: lookupTable[(int)DeclaredSymbolInfoKind.Class] = true; lookupTable[(int)DeclaredSymbolInfoKind.Record] = true; break; case NavigateToItemKind.Constant: lookupTable[(int)DeclaredSymbolInfoKind.Constant] = true; break; case NavigateToItemKind.Delegate: lookupTable[(int)DeclaredSymbolInfoKind.Delegate] = true; break; case NavigateToItemKind.Enum: lookupTable[(int)DeclaredSymbolInfoKind.Enum] = true; break; case NavigateToItemKind.EnumItem: lookupTable[(int)DeclaredSymbolInfoKind.EnumMember] = true; break; case NavigateToItemKind.Event: lookupTable[(int)DeclaredSymbolInfoKind.Event] = true; break; case NavigateToItemKind.Field: lookupTable[(int)DeclaredSymbolInfoKind.Field] = true; break; case NavigateToItemKind.Interface: lookupTable[(int)DeclaredSymbolInfoKind.Interface] = true; break; case NavigateToItemKind.Method: lookupTable[(int)DeclaredSymbolInfoKind.Constructor] = true; lookupTable[(int)DeclaredSymbolInfoKind.ExtensionMethod] = true; lookupTable[(int)DeclaredSymbolInfoKind.Method] = true; break; case NavigateToItemKind.Module: lookupTable[(int)DeclaredSymbolInfoKind.Module] = true; break; case NavigateToItemKind.Property: lookupTable[(int)DeclaredSymbolInfoKind.Indexer] = true; lookupTable[(int)DeclaredSymbolInfoKind.Property] = true; break; case NavigateToItemKind.Structure: lookupTable[(int)DeclaredSymbolInfoKind.Struct] = true; lookupTable[(int)DeclaredSymbolInfoKind.RecordStruct] = true; break; default: // Not a recognized symbol info kind break; } } _lookupTable = ImmutableArray.CreateRange(lookupTable); } public bool Contains(DeclaredSymbolInfoKind item) { return (int)item < _lookupTable.Length && _lookupTable[(int)item]; } } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { internal abstract partial class AbstractNavigateToSearchService { private static ImmutableArray<(PatternMatchKind roslynKind, NavigateToMatchKind vsKind)> s_kindPairs = ImmutableArray.Create( (PatternMatchKind.Exact, NavigateToMatchKind.Exact), (PatternMatchKind.Prefix, NavigateToMatchKind.Prefix), (PatternMatchKind.NonLowercaseSubstring, NavigateToMatchKind.Substring), (PatternMatchKind.StartOfWordSubstring, NavigateToMatchKind.Substring), (PatternMatchKind.CamelCaseExact, NavigateToMatchKind.CamelCaseExact), (PatternMatchKind.CamelCasePrefix, NavigateToMatchKind.CamelCasePrefix), (PatternMatchKind.CamelCaseNonContiguousPrefix, NavigateToMatchKind.CamelCaseNonContiguousPrefix), (PatternMatchKind.CamelCaseSubstring, NavigateToMatchKind.CamelCaseSubstring), (PatternMatchKind.CamelCaseNonContiguousSubstring, NavigateToMatchKind.CamelCaseNonContiguousSubstring), (PatternMatchKind.Fuzzy, NavigateToMatchKind.Fuzzy), // Map our value to 'Fuzzy' as that's the lower value the platform supports. (PatternMatchKind.LowercaseSubstring, NavigateToMatchKind.Fuzzy)); public static Task SearchFullyLoadedProjectInCurrentProcessAsync( Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { return FindSearchResultsAsync( project, priorityDocuments, searchDocument: null, pattern: searchPattern, kinds, onResultFound, cancellationToken); } public static Task SearchFullyLoadedDocumentInCurrentProcessAsync( Document document, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { return FindSearchResultsAsync( document.Project, priorityDocuments: ImmutableArray<Document>.Empty, document, searchPattern, kinds, onResultFound, cancellationToken); } private static async Task FindSearchResultsAsync( Project project, ImmutableArray<Document> priorityDocuments, Document? searchDocument, string pattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { // If the user created a dotted pattern then we'll grab the last part of the name var (patternName, patternContainerOpt) = PatternMatcher.GetNameAndContainer(pattern); var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds); // Prioritize the active documents if we have any. var highPriDocs = priorityDocuments.Where(d => project.ContainsDocument(d.Id)).ToSet(); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, highPriDocs, cancellationToken).ConfigureAwait(false); // Then process non-priority documents. var lowPriDocs = project.Documents.Where(d => !highPriDocs.Contains(d)).ToSet(); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, lowPriDocs, cancellationToken).ConfigureAwait(false); // if the caller is only searching a single doc, and we already covered it above, don't bother computing // source-generator docs. if (searchDocument != null && (highPriDocs.Contains(searchDocument) || lowPriDocs.Contains(searchDocument))) return; // Finally, generate and process and source-generated docs. this may take some time, so we always want to // do this after the other documents. var generatedDocs = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, generatedDocs.ToSet<Document>(), cancellationToken).ConfigureAwait(false); } private static async Task ProcessDocumentsAsync( Document? searchDocument, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, ISet<Document> documents, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var document in documents) { if (searchDocument != null && searchDocument != document) continue; cancellationToken.ThrowIfCancellationRequested(); tasks.Add(Task.Run(() => ProcessDocumentAsync(document, patternName, patternContainer, kinds, onResultFound, cancellationToken), cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static async Task ProcessDocumentAsync( Document document, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { var index = await SyntaxTreeIndex.GetRequiredIndexAsync(document, cancellationToken).ConfigureAwait(false); await ProcessIndexAsync( document.Id, document, patternName, patternContainer, kinds, onResultFound, index, cancellationToken).ConfigureAwait(false); } public static async Task SearchCachedDocumentsInCurrentProcessAsync( HostWorkspaceServices services, ImmutableArray<DocumentKey> documentKeys, ImmutableArray<DocumentKey> priorityDocumentKeys, StorageDatabase database, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onItemFound, CancellationToken cancellationToken) { var stringTable = new StringTable(); var highPriDocsSet = priorityDocumentKeys.ToSet(); var lowPriDocs = documentKeys.WhereAsArray(d => !highPriDocsSet.Contains(d)); // If the user created a dotted pattern then we'll grab the last part of the name var (patternName, patternContainer) = PatternMatcher.GetNameAndContainer(searchPattern); var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds); await SearchCachedDocumentsInCurrentProcessAsync( services, priorityDocumentKeys, database, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false); await SearchCachedDocumentsInCurrentProcessAsync( services, lowPriDocs, database, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false); } private static async Task SearchCachedDocumentsInCurrentProcessAsync( HostWorkspaceServices services, ImmutableArray<DocumentKey> documentKeys, StorageDatabase database, string patternName, string patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onItemFound, StringTable stringTable, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var documentKey in documentKeys) { tasks.Add(Task.Run(async () => { var index = await SyntaxTreeIndex.LoadAsync( services, documentKey, checksum: null, database, stringTable, cancellationToken).ConfigureAwait(false); if (index == null) return; await ProcessIndexAsync( documentKey.Id, document: null, patternName, patternContainer, kinds, onItemFound, index, cancellationToken).ConfigureAwait(false); }, cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static async Task ProcessIndexAsync( DocumentId documentId, Document? document, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, SyntaxTreeIndex index, CancellationToken cancellationToken) { var containerMatcher = patternContainer != null ? PatternMatcher.CreateDotSeparatedContainerMatcher(patternContainer) : null; using var nameMatcher = PatternMatcher.CreatePatternMatcher(patternName, includeMatchedSpans: true, allowFuzzyMatching: true); using var _1 = containerMatcher; foreach (var declaredSymbolInfo in index.DeclaredSymbolInfos) { // Namespaces are never returned in nav-to as they're too common and have too many locations. if (declaredSymbolInfo.Kind == DeclaredSymbolInfoKind.Namespace) continue; await AddResultIfMatchAsync( documentId, document, declaredSymbolInfo, nameMatcher, containerMatcher, kinds, onResultFound, cancellationToken).ConfigureAwait(false); } } private static async Task AddResultIfMatchAsync( DocumentId documentId, Document? document, DeclaredSymbolInfo declaredSymbolInfo, PatternMatcher nameMatcher, PatternMatcher? containerMatcher, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { using var nameMatches = TemporaryArray<PatternMatch>.Empty; using var containerMatches = TemporaryArray<PatternMatch>.Empty; cancellationToken.ThrowIfCancellationRequested(); if (kinds.Contains(declaredSymbolInfo.Kind) && nameMatcher.AddMatches(declaredSymbolInfo.Name, ref nameMatches.AsRef()) && containerMatcher?.AddMatches(declaredSymbolInfo.FullyQualifiedContainerName, ref containerMatches.AsRef()) != false) { // See if we have a match in a linked file. If so, see if we have the same match in // other projects that this file is linked in. If so, include the full set of projects // the match is in so we can display that well in the UI. // // We can only do this in the case where the solution is loaded and thus we can examine // the relationship between this document and the other documents linked to it. In the // case where the solution isn't fully loaded and we're just reading in cached data, we // don't know what other files we're linked to and can't merge results in this fashion. var additionalMatchingProjects = await GetAdditionalProjectsWithMatchAsync( document, declaredSymbolInfo, cancellationToken).ConfigureAwait(false); var result = ConvertResult( documentId, document, declaredSymbolInfo, nameMatches, containerMatches, additionalMatchingProjects); await onResultFound(result).ConfigureAwait(false); } } private static RoslynNavigateToItem ConvertResult( DocumentId documentId, Document? document, DeclaredSymbolInfo declaredSymbolInfo, in TemporaryArray<PatternMatch> nameMatches, in TemporaryArray<PatternMatch> containerMatches, ImmutableArray<ProjectId> additionalMatchingProjects) { var matchKind = GetNavigateToMatchKind(nameMatches); // A match is considered to be case sensitive if all its constituent pattern matches are // case sensitive. var isCaseSensitive = nameMatches.All(m => m.IsCaseSensitive) && containerMatches.All(m => m.IsCaseSensitive); var kind = GetItemKind(declaredSymbolInfo); using var matchedSpans = TemporaryArray<TextSpan>.Empty; foreach (var match in nameMatches) matchedSpans.AddRange(match.MatchedSpans); // If we were not given a Document instance, then we're finding matches in cached data // and thus could be 'stale'. return new RoslynNavigateToItem( isStale: document == null, documentId, additionalMatchingProjects, declaredSymbolInfo, kind, matchKind, isCaseSensitive, matchedSpans.ToImmutableAndClear()); } private static async ValueTask<ImmutableArray<ProjectId>> GetAdditionalProjectsWithMatchAsync( Document? document, DeclaredSymbolInfo declaredSymbolInfo, CancellationToken cancellationToken) { if (document == null) return ImmutableArray<ProjectId>.Empty; using var _ = ArrayBuilder<ProjectId>.GetInstance(out var result); var solution = document.Project.Solution; var linkedDocumentIds = document.GetLinkedDocumentIds(); foreach (var linkedDocumentId in linkedDocumentIds) { var linkedDocument = solution.GetRequiredDocument(linkedDocumentId); var index = await SyntaxTreeIndex.GetRequiredIndexAsync(linkedDocument, cancellationToken).ConfigureAwait(false); // See if the index for the other file also contains this same info. If so, merge the results so the // user only sees them as a single hit in the UI. if (index.DeclaredSymbolInfoSet.Contains(declaredSymbolInfo)) result.Add(linkedDocument.Project.Id); } result.RemoveDuplicates(); return result.ToImmutable(); } private static string GetItemKind(DeclaredSymbolInfo declaredSymbolInfo) { switch (declaredSymbolInfo.Kind) { case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Record: return NavigateToItemKind.Class; case DeclaredSymbolInfoKind.RecordStruct: return NavigateToItemKind.Structure; case DeclaredSymbolInfoKind.Constant: return NavigateToItemKind.Constant; case DeclaredSymbolInfoKind.Delegate: return NavigateToItemKind.Delegate; case DeclaredSymbolInfoKind.Enum: return NavigateToItemKind.Enum; case DeclaredSymbolInfoKind.EnumMember: return NavigateToItemKind.EnumItem; case DeclaredSymbolInfoKind.Event: return NavigateToItemKind.Event; case DeclaredSymbolInfoKind.Field: return NavigateToItemKind.Field; case DeclaredSymbolInfoKind.Interface: return NavigateToItemKind.Interface; case DeclaredSymbolInfoKind.Constructor: case DeclaredSymbolInfoKind.ExtensionMethod: case DeclaredSymbolInfoKind.Method: return NavigateToItemKind.Method; case DeclaredSymbolInfoKind.Module: return NavigateToItemKind.Module; case DeclaredSymbolInfoKind.Indexer: case DeclaredSymbolInfoKind.Property: return NavigateToItemKind.Property; case DeclaredSymbolInfoKind.Struct: return NavigateToItemKind.Structure; default: throw ExceptionUtilities.UnexpectedValue(declaredSymbolInfo.Kind); } } private static NavigateToMatchKind GetNavigateToMatchKind(in TemporaryArray<PatternMatch> nameMatches) { // work backwards through the match kinds. That way our result is as bad as our worst match part. For // example, say the user searches for `Console.Write` and we find `Console.Write` (exact, exact), and // `Console.WriteLine` (exact, prefix). We don't want the latter hit to be considered an `exact` match, and // thus as good as `Console.Write`. for (var i = s_kindPairs.Length - 1; i >= 0; i--) { var (roslynKind, vsKind) = s_kindPairs[i]; foreach (var match in nameMatches) { if (match.Kind == roslynKind) return vsKind; } } return NavigateToMatchKind.Regular; } private readonly struct DeclaredSymbolInfoKindSet { private readonly ImmutableArray<bool> _lookupTable; public DeclaredSymbolInfoKindSet(IEnumerable<string> navigateToItemKinds) { // The 'Contains' method implementation assumes that the DeclaredSymbolInfoKind type is unsigned. Debug.Assert(Enum.GetUnderlyingType(typeof(DeclaredSymbolInfoKind)) == typeof(byte)); var lookupTable = new bool[Enum.GetValues(typeof(DeclaredSymbolInfoKind)).Length]; foreach (var navigateToItemKind in navigateToItemKinds) { switch (navigateToItemKind) { case NavigateToItemKind.Class: lookupTable[(int)DeclaredSymbolInfoKind.Class] = true; lookupTable[(int)DeclaredSymbolInfoKind.Record] = true; break; case NavigateToItemKind.Constant: lookupTable[(int)DeclaredSymbolInfoKind.Constant] = true; break; case NavigateToItemKind.Delegate: lookupTable[(int)DeclaredSymbolInfoKind.Delegate] = true; break; case NavigateToItemKind.Enum: lookupTable[(int)DeclaredSymbolInfoKind.Enum] = true; break; case NavigateToItemKind.EnumItem: lookupTable[(int)DeclaredSymbolInfoKind.EnumMember] = true; break; case NavigateToItemKind.Event: lookupTable[(int)DeclaredSymbolInfoKind.Event] = true; break; case NavigateToItemKind.Field: lookupTable[(int)DeclaredSymbolInfoKind.Field] = true; break; case NavigateToItemKind.Interface: lookupTable[(int)DeclaredSymbolInfoKind.Interface] = true; break; case NavigateToItemKind.Method: lookupTable[(int)DeclaredSymbolInfoKind.Constructor] = true; lookupTable[(int)DeclaredSymbolInfoKind.ExtensionMethod] = true; lookupTable[(int)DeclaredSymbolInfoKind.Method] = true; break; case NavigateToItemKind.Module: lookupTable[(int)DeclaredSymbolInfoKind.Module] = true; break; case NavigateToItemKind.Property: lookupTable[(int)DeclaredSymbolInfoKind.Indexer] = true; lookupTable[(int)DeclaredSymbolInfoKind.Property] = true; break; case NavigateToItemKind.Structure: lookupTable[(int)DeclaredSymbolInfoKind.Struct] = true; lookupTable[(int)DeclaredSymbolInfoKind.RecordStruct] = true; break; default: // Not a recognized symbol info kind break; } } _lookupTable = ImmutableArray.CreateRange(lookupTable); } public bool Contains(DeclaredSymbolInfoKind item) { return (int)item < _lookupTable.Length && _lookupTable[(int)item]; } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxList.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal abstract partial class SyntaxList : GreenNode { internal SyntaxList() : base(GreenNode.ListKind) { } internal SyntaxList(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) : base(GreenNode.ListKind, diagnostics, annotations) { } internal SyntaxList(ObjectReader reader) : base(reader) { } internal static GreenNode List(GreenNode child) { return child; } internal static WithTwoChildren List(GreenNode child0, GreenNode child1) { RoslynDebug.Assert(child0 != null); RoslynDebug.Assert(child1 != null); int hash; GreenNode? cached = SyntaxNodeCache.TryGetNode(GreenNode.ListKind, child0, child1, out hash); if (cached != null) return (WithTwoChildren)cached; var result = new WithTwoChildren(child0, child1); if (hash >= 0) { SyntaxNodeCache.AddNode(result, hash); } return result; } internal static WithThreeChildren List(GreenNode child0, GreenNode child1, GreenNode child2) { RoslynDebug.Assert(child0 != null); RoslynDebug.Assert(child1 != null); RoslynDebug.Assert(child2 != null); int hash; GreenNode? cached = SyntaxNodeCache.TryGetNode(GreenNode.ListKind, child0, child1, child2, out hash); if (cached != null) return (WithThreeChildren)cached; var result = new WithThreeChildren(child0, child1, child2); if (hash >= 0) { SyntaxNodeCache.AddNode(result, hash); } return result; } internal static GreenNode List(GreenNode?[] nodes) { return List(nodes, nodes.Length); } internal static GreenNode List(GreenNode?[] nodes, int count) { var array = new ArrayElement<GreenNode>[count]; for (int i = 0; i < count; i++) { var node = nodes[i]; Debug.Assert(node is object); array[i].Value = node; } return List(array); } internal static SyntaxList List(ArrayElement<GreenNode>[] children) { // "WithLotsOfChildren" list will allocate a separate array to hold // precomputed node offsets. It may not be worth it for smallish lists. if (children.Length < 10) { return new WithManyChildren(children); } else { return new WithLotsOfChildren(children); } } internal abstract void CopyTo(ArrayElement<GreenNode>[] array, int offset); internal static GreenNode? Concat(GreenNode? left, GreenNode? right) { if (left == null) { return right; } if (right == null) { return left; } var leftList = left as SyntaxList; var rightList = right as SyntaxList; if (leftList != null) { if (rightList != null) { var tmp = new ArrayElement<GreenNode>[left.SlotCount + right.SlotCount]; leftList.CopyTo(tmp, 0); rightList.CopyTo(tmp, left.SlotCount); return List(tmp); } else { var tmp = new ArrayElement<GreenNode>[left.SlotCount + 1]; leftList.CopyTo(tmp, 0); tmp[left.SlotCount].Value = right; return List(tmp); } } else if (rightList != null) { var tmp = new ArrayElement<GreenNode>[rightList.SlotCount + 1]; tmp[0].Value = left; rightList.CopyTo(tmp, 1); return List(tmp); } else { return List(left, right); } } public sealed override string Language { get { throw ExceptionUtilities.Unreachable; } } public sealed override string KindText { get { throw ExceptionUtilities.Unreachable; } } public sealed override SyntaxNode GetStructure(SyntaxTrivia parentTrivia) { throw ExceptionUtilities.Unreachable; } public sealed override SyntaxToken CreateSeparator<TNode>(SyntaxNode element) { throw ExceptionUtilities.Unreachable; } public sealed override bool IsTriviaWithEndOfLine() { 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.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal abstract partial class SyntaxList : GreenNode { internal SyntaxList() : base(GreenNode.ListKind) { } internal SyntaxList(DiagnosticInfo[]? diagnostics, SyntaxAnnotation[]? annotations) : base(GreenNode.ListKind, diagnostics, annotations) { } internal SyntaxList(ObjectReader reader) : base(reader) { } internal static GreenNode List(GreenNode child) { return child; } internal static WithTwoChildren List(GreenNode child0, GreenNode child1) { RoslynDebug.Assert(child0 != null); RoslynDebug.Assert(child1 != null); int hash; GreenNode? cached = SyntaxNodeCache.TryGetNode(GreenNode.ListKind, child0, child1, out hash); if (cached != null) return (WithTwoChildren)cached; var result = new WithTwoChildren(child0, child1); if (hash >= 0) { SyntaxNodeCache.AddNode(result, hash); } return result; } internal static WithThreeChildren List(GreenNode child0, GreenNode child1, GreenNode child2) { RoslynDebug.Assert(child0 != null); RoslynDebug.Assert(child1 != null); RoslynDebug.Assert(child2 != null); int hash; GreenNode? cached = SyntaxNodeCache.TryGetNode(GreenNode.ListKind, child0, child1, child2, out hash); if (cached != null) return (WithThreeChildren)cached; var result = new WithThreeChildren(child0, child1, child2); if (hash >= 0) { SyntaxNodeCache.AddNode(result, hash); } return result; } internal static GreenNode List(GreenNode?[] nodes) { return List(nodes, nodes.Length); } internal static GreenNode List(GreenNode?[] nodes, int count) { var array = new ArrayElement<GreenNode>[count]; for (int i = 0; i < count; i++) { var node = nodes[i]; Debug.Assert(node is object); array[i].Value = node; } return List(array); } internal static SyntaxList List(ArrayElement<GreenNode>[] children) { // "WithLotsOfChildren" list will allocate a separate array to hold // precomputed node offsets. It may not be worth it for smallish lists. if (children.Length < 10) { return new WithManyChildren(children); } else { return new WithLotsOfChildren(children); } } internal abstract void CopyTo(ArrayElement<GreenNode>[] array, int offset); internal static GreenNode? Concat(GreenNode? left, GreenNode? right) { if (left == null) { return right; } if (right == null) { return left; } var leftList = left as SyntaxList; var rightList = right as SyntaxList; if (leftList != null) { if (rightList != null) { var tmp = new ArrayElement<GreenNode>[left.SlotCount + right.SlotCount]; leftList.CopyTo(tmp, 0); rightList.CopyTo(tmp, left.SlotCount); return List(tmp); } else { var tmp = new ArrayElement<GreenNode>[left.SlotCount + 1]; leftList.CopyTo(tmp, 0); tmp[left.SlotCount].Value = right; return List(tmp); } } else if (rightList != null) { var tmp = new ArrayElement<GreenNode>[rightList.SlotCount + 1]; tmp[0].Value = left; rightList.CopyTo(tmp, 1); return List(tmp); } else { return List(left, right); } } public sealed override string Language { get { throw ExceptionUtilities.Unreachable; } } public sealed override string KindText { get { throw ExceptionUtilities.Unreachable; } } public sealed override SyntaxNode GetStructure(SyntaxTrivia parentTrivia) { throw ExceptionUtilities.Unreachable; } public sealed override SyntaxToken CreateSeparator<TNode>(SyntaxNode element) { throw ExceptionUtilities.Unreachable; } public sealed override bool IsTriviaWithEndOfLine() { return false; } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Features/VisualBasic/Portable/CodeFixes/ConvertToAsync/VisualBasicConvertToAsyncFunctionCodeFixProvider.vb
' 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. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.Async Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.ConvertToAsync <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.ConvertToAsync), [Shared]> Friend Class VisualBasicConvertToAsyncFunctionCodeFixProvider Inherits AbstractConvertToAsyncCodeFixProvider Friend Const BC37001 As String = "BC37001" ' error BC37001: 'Blah' Does not return a Task and is not awaited consider changing to an Async Function. Friend ReadOnly Ids As ImmutableArray(Of String) = ImmutableArray.Create(Of String)(BC37001) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return Ids End Get End Property Protected Overrides Async Function GetDescriptionAsync(diagnostic As Diagnostic, node As SyntaxNode, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Task(Of String) Dim methodNode = Await GetMethodFromExpressionAsync(node, semanticModel, cancellationToken).ConfigureAwait(False) Return String.Format(VBFeaturesResources.Make_0_an_Async_Function, methodNode.Item2.BlockStatement) End Function Protected Overrides Async Function GetRootInOtherSyntaxTreeAsync(node As SyntaxNode, semanticModel As SemanticModel, diagnostic As Diagnostic, cancellationToken As CancellationToken) As Task(Of Tuple(Of SyntaxTree, SyntaxNode)) Dim tuple = Await GetMethodFromExpressionAsync(node, semanticModel, cancellationToken).ConfigureAwait(False) If tuple Is Nothing Then Return Nothing End If Dim oldRoot = tuple.Item1 Dim methodBlock = tuple.Item2 Dim newRoot = oldRoot.ReplaceNode(methodBlock, ConvertToAsyncFunction(methodBlock)) Return System.Tuple.Create(oldRoot.SyntaxTree, newRoot) End Function Private Shared Async Function GetMethodFromExpressionAsync(oldNode As SyntaxNode, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Task(Of Tuple(Of SyntaxNode, MethodBlockSyntax)) If oldNode Is Nothing Then Return Nothing End If Dim methodSymbol = TryCast(semanticModel.GetSymbolInfo(oldNode, cancellationToken).Symbol, IMethodSymbol) If methodSymbol Is Nothing Then Return Nothing End If Dim methodReference = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault() If methodReference Is Nothing Then Return Nothing End If Dim root = Await methodReference.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(False) Dim methodDeclaration = TryCast(Await methodReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(False), MethodStatementSyntax) If methodDeclaration Is Nothing Then Return Nothing End If If Not methodDeclaration.IsKind(SyntaxKind.SubStatement) Then Return Nothing End If Dim methodBlock = methodDeclaration.GetAncestor(Of MethodBlockSyntax) If methodBlock Is Nothing Then Return Nothing End If Return Tuple.Create(root, methodBlock) End Function Private Shared Function ConvertToAsyncFunction(methodBlock As MethodBlockSyntax) As MethodBlockSyntax Dim methodNode = methodBlock.SubOrFunctionStatement Dim blockBegin = SyntaxFactory.FunctionStatement( methodNode.AttributeLists, methodNode.Modifiers, methodNode.Identifier, methodNode.TypeParameterList, methodNode.ParameterList.WithoutTrailingTrivia(), SyntaxFactory.SimpleAsClause(SyntaxFactory.ParseTypeName("Task")) _ .WithTrailingTrivia(methodNode.ParameterList.GetTrailingTrivia()), methodNode.HandlesClause, methodNode.ImplementsClause) _ .WithAdditionalAnnotations(Formatter.Annotation) Dim blockEnd = SyntaxFactory.EndBlockStatement(SyntaxKind.EndFunctionStatement, SyntaxFactory.Token(SyntaxKind.FunctionKeyword)) _ .WithLeadingTrivia(methodBlock.EndBlockStatement.GetLeadingTrivia()) _ .WithTrailingTrivia(methodBlock.EndBlockStatement.GetTrailingTrivia()) _ .WithAdditionalAnnotations(Formatter.Annotation) Return SyntaxFactory.FunctionBlock(blockBegin, methodBlock.Statements, blockEnd) End Function End Class End Namespace
' 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. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.Async Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.ConvertToAsync <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.ConvertToAsync), [Shared]> Friend Class VisualBasicConvertToAsyncFunctionCodeFixProvider Inherits AbstractConvertToAsyncCodeFixProvider Friend Const BC37001 As String = "BC37001" ' error BC37001: 'Blah' Does not return a Task and is not awaited consider changing to an Async Function. Friend ReadOnly Ids As ImmutableArray(Of String) = ImmutableArray.Create(Of String)(BC37001) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return Ids End Get End Property Protected Overrides Async Function GetDescriptionAsync(diagnostic As Diagnostic, node As SyntaxNode, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Task(Of String) Dim methodNode = Await GetMethodFromExpressionAsync(node, semanticModel, cancellationToken).ConfigureAwait(False) Return String.Format(VBFeaturesResources.Make_0_an_Async_Function, methodNode.Item2.BlockStatement) End Function Protected Overrides Async Function GetRootInOtherSyntaxTreeAsync(node As SyntaxNode, semanticModel As SemanticModel, diagnostic As Diagnostic, cancellationToken As CancellationToken) As Task(Of Tuple(Of SyntaxTree, SyntaxNode)) Dim tuple = Await GetMethodFromExpressionAsync(node, semanticModel, cancellationToken).ConfigureAwait(False) If tuple Is Nothing Then Return Nothing End If Dim oldRoot = tuple.Item1 Dim methodBlock = tuple.Item2 Dim newRoot = oldRoot.ReplaceNode(methodBlock, ConvertToAsyncFunction(methodBlock)) Return System.Tuple.Create(oldRoot.SyntaxTree, newRoot) End Function Private Shared Async Function GetMethodFromExpressionAsync(oldNode As SyntaxNode, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Task(Of Tuple(Of SyntaxNode, MethodBlockSyntax)) If oldNode Is Nothing Then Return Nothing End If Dim methodSymbol = TryCast(semanticModel.GetSymbolInfo(oldNode, cancellationToken).Symbol, IMethodSymbol) If methodSymbol Is Nothing Then Return Nothing End If Dim methodReference = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault() If methodReference Is Nothing Then Return Nothing End If Dim root = Await methodReference.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(False) Dim methodDeclaration = TryCast(Await methodReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(False), MethodStatementSyntax) If methodDeclaration Is Nothing Then Return Nothing End If If Not methodDeclaration.IsKind(SyntaxKind.SubStatement) Then Return Nothing End If Dim methodBlock = methodDeclaration.GetAncestor(Of MethodBlockSyntax) If methodBlock Is Nothing Then Return Nothing End If Return Tuple.Create(root, methodBlock) End Function Private Shared Function ConvertToAsyncFunction(methodBlock As MethodBlockSyntax) As MethodBlockSyntax Dim methodNode = methodBlock.SubOrFunctionStatement Dim blockBegin = SyntaxFactory.FunctionStatement( methodNode.AttributeLists, methodNode.Modifiers, methodNode.Identifier, methodNode.TypeParameterList, methodNode.ParameterList.WithoutTrailingTrivia(), SyntaxFactory.SimpleAsClause(SyntaxFactory.ParseTypeName("Task")) _ .WithTrailingTrivia(methodNode.ParameterList.GetTrailingTrivia()), methodNode.HandlesClause, methodNode.ImplementsClause) _ .WithAdditionalAnnotations(Formatter.Annotation) Dim blockEnd = SyntaxFactory.EndBlockStatement(SyntaxKind.EndFunctionStatement, SyntaxFactory.Token(SyntaxKind.FunctionKeyword)) _ .WithLeadingTrivia(methodBlock.EndBlockStatement.GetLeadingTrivia()) _ .WithTrailingTrivia(methodBlock.EndBlockStatement.GetTrailingTrivia()) _ .WithAdditionalAnnotations(Formatter.Annotation) Return SyntaxFactory.FunctionBlock(blockBegin, methodBlock.Statements, blockEnd) End Function End Class End Namespace
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/EditorFeatures/Test2/Rename/InlineRenameTests.vb
' 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. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class InlineRenameTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function SimpleEditAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLocalVariableInTopLevelStatement(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> object [|$$test|] = new object(); var other = [|test|]; </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "renamed") session.Commit() Await VerifyTagsAreCorrect(workspace, "renamedtest") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLambdaDiscard(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void M() { C _ = null; System.Func<int, string, int> f = (int _, string [|$$_|]) => { _ = null; return 1; }; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="_", renameTextPrefix:="change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(46208, "https://github.com/dotnet/roslyn/issues/46208")> Public Async Function RenameWithInvalidIdentifier(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|Test1$$|] { } ]]></Document> </Project> </Workspace>, host) Dim options = workspace.CurrentSolution.Options workspace.TryApplyChanges( workspace.CurrentSolution.WithOptions(options.WithChangedOption(RenameOptions.RenameFile, True))) Dim session = StartSession(workspace) Dim selectedSpan = workspace.DocumentWithCursor.CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' User could use copy & paste to enter invalid character textBuffer.Insert(selectedSpan, "<>") session.Commit() Await VerifyTagsAreCorrect(workspace, "Test1<>") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")> Public Async Function RenameDeconstructionForeachCollection(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> [|$$x|]) { foreach (var (y1, y2) in [|x|]) { } } void Deconstruct(out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "x", "change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameDeconstructMethodInDeconstructionForeach(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> x) { foreach (var (y1, y2) in x) { } var (z1, z2) = this; [|Deconstruct|](out var t1, out var t2); } void [|$$Deconstruct|](out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "Deconstruct", "Changed", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(540120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540120")> Public Async Function SimpleEditAndVerifyTagsPropagatedAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function Private Shared Async Function VerifyRenameOptionChangedSessionCommit(workspace As TestWorkspace, originalTextToRename As String, renameTextPrefix As String, Optional renameOverloads As Boolean = False, Optional renameInStrings As Boolean = False, Optional renameInComments As Boolean = False, Optional renameFile As Boolean = False, Optional fileToRename As DocumentId = Nothing) As Task Dim optionSet = workspace.Options optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, renameOverloads) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInStrings, renameInStrings) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInComments, renameInComments) optionSet = optionSet.WithChangedOption(RenameOptions.RenameFile, renameFile) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)) Dim session = StartSession(workspace) ' Type a bit in the file Dim renameDocument As TestHostDocument = workspace.DocumentWithCursor renameDocument.GetTextBuffer().Insert(renameDocument.CursorPosition.Value, renameTextPrefix) Dim replacementText = renameTextPrefix + originalTextToRename Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, replacementText) session.Commit() Await VerifyTagsAreCorrect(workspace, replacementText) If renameFile Then If fileToRename Is Nothing Then VerifyFileName(workspace, replacementText) Else VerifyFileName(workspace.CurrentSolution.GetDocument(fileToRename), replacementText) End If End If End Function <WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/13186")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { public void [|$$goo|]() { [|goo|](); } public void [|goo|]&lt;T&gt;() { [|goo|]&lt;T&gt;(); } public void [|goo|](int i) { [|goo|](i); } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Imports System.Linq Imports System Public Class Program Sub Main(args As String()) End Sub Public Sub [|$$goo|]() [|goo|]() End Sub Public Sub [|goo|](of T)() [|goo|](of T)() End Sub Public Sub [|goo|](s As String) [|goo|](s) End Sub Public Shared Sub [|goo|](d As Double) [|goo|](d) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(960955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960955")> Public Async Function RenameParameterShouldNotAffectCommentsInOtherDocuments(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Program Sub Main([|$$args|] As String()) End Sub End Class </Document> <Document> ' args </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "args", "bar", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "Test1.vb")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesDoesNotCrash(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) ' https://github.com/dotnet/roslyn/issues/36075 ' VerifyFileRename(workspace, "ABC") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesHandlesBothProjects(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class [|$$C|] { } // [|C|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|C|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPrivateAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { private void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // F ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPublicAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { public void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // [|F|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3623, "https://github.com/dotnet/roslyn/issues/3623")> Public Async Function RenameTypeInLinkedFiles(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"><![CDATA[ public class [|$$C|] { } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB") Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.goo(System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void [|goo|](int i) { [|goo|](i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "[|goo|]"; var b = $"{1}[|goo|]{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.goo(System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub [|goo|](i As Integer) [|goo|](i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "[|goo|]" Dim b = $"{1}[|goo|]{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub SimpleEditAndCancel(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim initialTextSnapshot = textBuffer.CurrentSnapshot textBuffer.Insert(caretPosition, "Bar") session.Cancel() ' Assert the file is what it started as Assert.Equal(initialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText()) ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <WorkItem(539513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539513")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CanRenameTypeNamedDynamic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$dynamic|] { void M() { [|dynamic|] d; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "goo") session.Commit() Await VerifyTagsAreCorrect(workspace, "goodynamic") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ReadOnlyRegionsCreated(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$C { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Dim cursorPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.False(buffer.IsReadOnly(cursorPosition)) Assert.False(buffer.IsReadOnly(cursorPosition + 1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) ' Make sure we can't type at the start or end Assert.True(buffer.IsReadOnly(0)) Assert.True(buffer.IsReadOnly(buffer.CurrentSnapshot.Length)) session.Cancel() ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543018")> Public Sub ReadOnlyRegionsCreatedWhichHandleBeginningOfFileEdgeCase(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>$$C c; class C { }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Assert.False(buffer.IsReadOnly(0)) Assert.False(buffer.IsReadOnly(1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) session.Cancel() VerifyFileName(workspace, "Test1.cs") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameWithInheritenceCascadingWithClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> abstract class AAAA { public abstract void [|Goo|](); } class BBBB : AAAA { public override void [|Goo|]() { } } class DDDD : BBBB { public override void [|Goo|]() { } } class CCCC : AAAA { public override void [|$$Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="GooBar") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530467")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping2(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(579210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579210")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530765")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCancel(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarGoo") session.Cancel() Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyRenameTrackingWorksAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") textBuffer.Insert(caretPosition, "Baz") Await VerifyRenameTrackingTags(renameTrackingTagger, workspace, document, expectedTagCount:=1) End Using End Function <WpfTheory, WorkItem(978099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/978099")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) ' Preview should not return null Dim previewService = DirectCast(workspace.Services.GetRequiredService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = False Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) Assert.Equal(String.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), previewService.Title) Assert.Equal(String.Format(EditorFeaturesResources.Rename_0_to_1_colon, "Goo", "BarGoo"), previewService.Description) Assert.Equal("Goo", previewService.TopLevelName) Assert.Equal(Glyph.ClassInternal, previewService.TopLevelGlyph) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCancellation(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim previewService = DirectCast(workspace.Services.GetService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = True Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) ' Session should still be up; type some more caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Insert(caretPosition, "Cat") previewService.ReturnsNull = False previewService.Called = False session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "CatBarGoo") Assert.True(previewService.Called) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_MethodWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Sub [|M$$|]() End Sub Sub Test() #If Proj1 Then [|M|]() #End If #If Proj2 Then [|M|]() #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "o") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mo") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mow") session.Commit() Await VerifyTagsAreCorrect(workspace, "Mow") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_FieldWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Dim [|m$$|] As Integer Sub Test() #If Proj1 Then Dim x = [|m|] #End If #If Proj2 Then Dim x = [|m|] #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "ma") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "maw") session.Commit() Await VerifyTagsAreCorrect(workspace, "maw") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(554, "https://github.com/dotnet/roslyn/issues/554")> Public Async Function CodeActionCannotCommitDuringInlineRename(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { void M() { var z = {|introducelocal:5 + 5|}; var q = [|x$$|]; } int [|x|]; }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "yz") Await WaitForRename(workspace) ' Invoke a CodeAction Dim introduceVariableRefactoringProvider = New IntroduceVariableCodeRefactoringProvider() Dim actions = New List(Of CodeAction) Dim context = New CodeRefactoringContext( workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), workspace.Documents.Single().AnnotatedSpans()("introducelocal").Single(), Sub(a) actions.Add(a), CancellationToken.None) workspace.Documents.Single().AnnotatedSpans.Clear() introduceVariableRefactoringProvider.ComputeRefactoringsAsync(context).Wait() Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService) Dim actualSeverity As NotificationSeverity = Nothing Dim notificationService = DirectCast(workspace.Services.GetService(Of INotificationService)(), INotificationServiceCallback) notificationService.NotificationCallback = Sub(message, title, severity) actualSeverity = severity editHandler.Apply( workspace, workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), Await actions.First().NestedCodeActions.First().GetOperationsAsync(CancellationToken.None), "unused", New ProgressTracker(), CancellationToken.None) ' CodeAction should be rejected Assert.Equal(NotificationSeverity.Error, actualSeverity) Assert.Equal(" class C { void M() { var z = 5 + 5; var q = xyz; } int xyz; }", textBuffer.CurrentSnapshot.GetText()) ' Rename should still be active Await VerifyTagsAreCorrect(workspace, "xyz") textBuffer.Insert(caretPosition + 2, "q") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "xyzq") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof([|M|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof(M).ToString(); } void M(int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads_WithRenameOverloadsOption(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|$$M|]() { nameof([|M|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "M", "Sa", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1142095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1142095")> Public Async Function RenameCommitsWhenDebuggingStarts(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") ' Make sure the RenameService's ActiveSession is still there Dim renameService = workspace.GetService(Of IInlineRenameService)() Assert.NotNull(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") ' Simulate starting a debugging session Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService) debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run) ' Ensure the rename was committed Assert.Null(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1142095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1142095")> Public Async Function RenameCommitsWhenExitingDebuggingBreakMode(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") ' Make sure the RenameService's ActiveSession is still there Dim renameService = workspace.GetService(Of IInlineRenameService)() Assert.NotNull(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") ' Simulate ending break mode in the debugger (by stepping or continuing) Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService) debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run) ' Ensure the rename was committed Assert.Null(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3316, "https://github.com/dotnet/roslyn/issues/3316")> Public Async Function InvalidInvocationExpression(host As RenameTestHost) As Task ' Everything on the last line of main is parsed as a single invocation expression ' with CType(...) as the receiver and everything else as arguments. ' Rename doesn't expect to see CType as the receiver of an invocation. Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Module1 Sub Main() Dim [|$$p|] As IEnumerable(Of Integer) = {1, 2, 3} Dim linked = Enumerable.Aggregate(Of Global.&lt;anonymous type:head As Global.System.Int32, tail As Global.System.Object&gt;)( CType([|p|], IEnumerable(Of Integer)), Nothing, Function(total, curr) Nothing) End Sub End Module </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "q") session.Commit() Await VerifyTagsAreCorrect(workspace, "qp") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(2445, "https://github.com/dotnet/roslyn/issues/2445")> Public Async Function InvalidExpansionTarget(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> int x; x = 2; void [|$$M|]() { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "x") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(9117, "https://github.com/dotnet/roslyn/issues/9117")> Public Async Function VerifyVBRenameCrashDoesNotRepro(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class1 Public Property [|$$Field1|] As Integer End Class Public Class Class2 Public Shared Property DataSource As IEnumerable(Of Class1) Public ReadOnly Property Dict As IReadOnlyDictionary(Of Integer, IEnumerable(Of Class1)) = ( From data In DataSource Group By data.Field1 Into Group1 = Group ).ToDictionary( Function(group) group.Field1, Function(group) group.Group1) End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "xield1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(14554, "https://github.com/dotnet/roslyn/issues/14554")> Public Sub VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub New(a As Action) End Sub Public ReadOnly Property Vm As C Public ReadOnly Property Crash As New C(Sub() Vm.Sav() End Sub) Public Function Sav$$() As Boolean Return False End Function Public Function Save() As Boolean Return False End Function End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' Ensure the rename doesn't crash textBuffer.Insert(caretPosition, "e") session.Commit() End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedForPartialType(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Goo|] { void Blah() { } } </Document> <Document> partial class Goo { void BlahBlah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeWithMultipleLocations, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedForPartialTypeWithSingleLocation(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Test1|] { void Blah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedWithMultipleTypesOnMatchingName(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { } } class Test2 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedWithMultipleTypes(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { } } class Test1 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeDoesNotMatchFileName, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyEnumKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum [|$$Test1|] { One, Two, Three } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyInterfaceKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface [|$$Test1|] { void Blah(); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyUnsupportedFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface Test1 { void [|$$Blah|](); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameNotAllowedForLinkedFiles(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) ' Disable document changes to make sure file rename is not supported. ' Linked workspace files will report that applying changes to document ' info is not allowed; this is intended to mimic that behavior ' and make sure inline rename works as intended. workspace.CanApplyChangeDocument = False Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "t") session.Commit() VerifyFileName(workspace, "test1") End Using End Sub <WpfTheory, WorkItem(36063, "https://github.com/dotnet/roslyn/issues/36063")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function EditBackToOriginalNameThenCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") textBuffer.Delete(New Span(caretPosition, "Bar".Length)) Dim committed = session.GetTestAccessor().CommitWorker(previewChanges:=False) Assert.False(committed) Await VerifyTagsAreCorrect(workspace, "Test1") End Using End Function <WpfTheory, WorkItem(44576, "https://github.com/dotnet/roslyn/issues/44576")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameFromOtherFile(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test1 { void Blah() { [|$$Test2|] t2 = new [|Test2|](); } } </Document> <Document Name="Test2.cs"> class Test2 { } </Document> </Project> </Workspace>, host) Dim docToRename = workspace.Documents.First(Function(doc) doc.Name = "Test2.cs") Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="Test2", renameTextPrefix:="Test2Changed", renameFile:=True, fileToRename:=docToRename.Id) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameConstructorReferencedInGlobalSuppression(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:[|C|].#ctor")] class [|C|] { public [|$$C|]() { } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "D") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithNoBody1(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a); class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithBody(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordConstructorCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g = new [|Goo|](1); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameExtendedProperty(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class C { void M() { _ = this is { Other.[|Goo|]: not null, Other.Other.[|Goo|]: not null, [|Goo|]: null } ; } public C [|$$Goo|] { get; set; } public C Other { get; set; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameInComment(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class [|$$MyClass|] { /// <summary> /// Initializes <see cref="MyClass"/>; /// </summary> MyClass() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) session.ApplyReplacementText("Example", True) session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInComments, True) session.Commit() Await VerifyTagsAreCorrect(workspace, "Example") End Using End Function End Class End Namespace
' 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. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class InlineRenameTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function SimpleEditAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLocalVariableInTopLevelStatement(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> object [|$$test|] = new object(); var other = [|test|]; </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "renamed") session.Commit() Await VerifyTagsAreCorrect(workspace, "renamedtest") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLambdaDiscard(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void M() { C _ = null; System.Func<int, string, int> f = (int _, string [|$$_|]) => { _ = null; return 1; }; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="_", renameTextPrefix:="change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(46208, "https://github.com/dotnet/roslyn/issues/46208")> Public Async Function RenameWithInvalidIdentifier(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|Test1$$|] { } ]]></Document> </Project> </Workspace>, host) Dim options = workspace.CurrentSolution.Options workspace.TryApplyChanges( workspace.CurrentSolution.WithOptions(options.WithChangedOption(RenameOptions.RenameFile, True))) Dim session = StartSession(workspace) Dim selectedSpan = workspace.DocumentWithCursor.CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' User could use copy & paste to enter invalid character textBuffer.Insert(selectedSpan, "<>") session.Commit() Await VerifyTagsAreCorrect(workspace, "Test1<>") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")> Public Async Function RenameDeconstructionForeachCollection(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> [|$$x|]) { foreach (var (y1, y2) in [|x|]) { } } void Deconstruct(out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "x", "change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameDeconstructMethodInDeconstructionForeach(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> x) { foreach (var (y1, y2) in x) { } var (z1, z2) = this; [|Deconstruct|](out var t1, out var t2); } void [|$$Deconstruct|](out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "Deconstruct", "Changed", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(540120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540120")> Public Async Function SimpleEditAndVerifyTagsPropagatedAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function Private Shared Async Function VerifyRenameOptionChangedSessionCommit(workspace As TestWorkspace, originalTextToRename As String, renameTextPrefix As String, Optional renameOverloads As Boolean = False, Optional renameInStrings As Boolean = False, Optional renameInComments As Boolean = False, Optional renameFile As Boolean = False, Optional fileToRename As DocumentId = Nothing) As Task Dim optionSet = workspace.Options optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, renameOverloads) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInStrings, renameInStrings) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInComments, renameInComments) optionSet = optionSet.WithChangedOption(RenameOptions.RenameFile, renameFile) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)) Dim session = StartSession(workspace) ' Type a bit in the file Dim renameDocument As TestHostDocument = workspace.DocumentWithCursor renameDocument.GetTextBuffer().Insert(renameDocument.CursorPosition.Value, renameTextPrefix) Dim replacementText = renameTextPrefix + originalTextToRename Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, replacementText) session.Commit() Await VerifyTagsAreCorrect(workspace, replacementText) If renameFile Then If fileToRename Is Nothing Then VerifyFileName(workspace, replacementText) Else VerifyFileName(workspace.CurrentSolution.GetDocument(fileToRename), replacementText) End If End If End Function <WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/13186")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { public void [|$$goo|]() { [|goo|](); } public void [|goo|]&lt;T&gt;() { [|goo|]&lt;T&gt;(); } public void [|goo|](int i) { [|goo|](i); } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Imports System.Linq Imports System Public Class Program Sub Main(args As String()) End Sub Public Sub [|$$goo|]() [|goo|]() End Sub Public Sub [|goo|](of T)() [|goo|](of T)() End Sub Public Sub [|goo|](s As String) [|goo|](s) End Sub Public Shared Sub [|goo|](d As Double) [|goo|](d) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(960955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960955")> Public Async Function RenameParameterShouldNotAffectCommentsInOtherDocuments(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Program Sub Main([|$$args|] As String()) End Sub End Class </Document> <Document> ' args </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "args", "bar", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "Test1.vb")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesDoesNotCrash(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) ' https://github.com/dotnet/roslyn/issues/36075 ' VerifyFileRename(workspace, "ABC") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesHandlesBothProjects(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class [|$$C|] { } // [|C|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|C|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPrivateAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { private void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // F ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPublicAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { public void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // [|F|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3623, "https://github.com/dotnet/roslyn/issues/3623")> Public Async Function RenameTypeInLinkedFiles(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"><![CDATA[ public class [|$$C|] { } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB") Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.goo(System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void [|goo|](int i) { [|goo|](i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "[|goo|]"; var b = $"{1}[|goo|]{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.goo(System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub [|goo|](i As Integer) [|goo|](i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "[|goo|]" Dim b = $"{1}[|goo|]{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub SimpleEditAndCancel(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim initialTextSnapshot = textBuffer.CurrentSnapshot textBuffer.Insert(caretPosition, "Bar") session.Cancel() ' Assert the file is what it started as Assert.Equal(initialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText()) ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <WorkItem(539513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539513")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CanRenameTypeNamedDynamic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$dynamic|] { void M() { [|dynamic|] d; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "goo") session.Commit() Await VerifyTagsAreCorrect(workspace, "goodynamic") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ReadOnlyRegionsCreated(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$C { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Dim cursorPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.False(buffer.IsReadOnly(cursorPosition)) Assert.False(buffer.IsReadOnly(cursorPosition + 1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) ' Make sure we can't type at the start or end Assert.True(buffer.IsReadOnly(0)) Assert.True(buffer.IsReadOnly(buffer.CurrentSnapshot.Length)) session.Cancel() ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543018")> Public Sub ReadOnlyRegionsCreatedWhichHandleBeginningOfFileEdgeCase(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>$$C c; class C { }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Assert.False(buffer.IsReadOnly(0)) Assert.False(buffer.IsReadOnly(1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) session.Cancel() VerifyFileName(workspace, "Test1.cs") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameWithInheritenceCascadingWithClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> abstract class AAAA { public abstract void [|Goo|](); } class BBBB : AAAA { public override void [|Goo|]() { } } class DDDD : BBBB { public override void [|Goo|]() { } } class CCCC : AAAA { public override void [|$$Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="GooBar") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530467")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping2(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(579210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579210")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530765")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCancel(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarGoo") session.Cancel() Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyRenameTrackingWorksAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") textBuffer.Insert(caretPosition, "Baz") Await VerifyRenameTrackingTags(renameTrackingTagger, workspace, document, expectedTagCount:=1) End Using End Function <WpfTheory, WorkItem(978099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/978099")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) ' Preview should not return null Dim previewService = DirectCast(workspace.Services.GetRequiredService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = False Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) Assert.Equal(String.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), previewService.Title) Assert.Equal(String.Format(EditorFeaturesResources.Rename_0_to_1_colon, "Goo", "BarGoo"), previewService.Description) Assert.Equal("Goo", previewService.TopLevelName) Assert.Equal(Glyph.ClassInternal, previewService.TopLevelGlyph) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCancellation(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim previewService = DirectCast(workspace.Services.GetService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = True Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) ' Session should still be up; type some more caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Insert(caretPosition, "Cat") previewService.ReturnsNull = False previewService.Called = False session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "CatBarGoo") Assert.True(previewService.Called) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_MethodWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Sub [|M$$|]() End Sub Sub Test() #If Proj1 Then [|M|]() #End If #If Proj2 Then [|M|]() #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "o") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mo") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mow") session.Commit() Await VerifyTagsAreCorrect(workspace, "Mow") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_FieldWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Dim [|m$$|] As Integer Sub Test() #If Proj1 Then Dim x = [|m|] #End If #If Proj2 Then Dim x = [|m|] #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "ma") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "maw") session.Commit() Await VerifyTagsAreCorrect(workspace, "maw") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(554, "https://github.com/dotnet/roslyn/issues/554")> Public Async Function CodeActionCannotCommitDuringInlineRename(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { void M() { var z = {|introducelocal:5 + 5|}; var q = [|x$$|]; } int [|x|]; }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "yz") Await WaitForRename(workspace) ' Invoke a CodeAction Dim introduceVariableRefactoringProvider = New IntroduceVariableCodeRefactoringProvider() Dim actions = New List(Of CodeAction) Dim context = New CodeRefactoringContext( workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), workspace.Documents.Single().AnnotatedSpans()("introducelocal").Single(), Sub(a) actions.Add(a), CancellationToken.None) workspace.Documents.Single().AnnotatedSpans.Clear() introduceVariableRefactoringProvider.ComputeRefactoringsAsync(context).Wait() Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService) Dim actualSeverity As NotificationSeverity = Nothing Dim notificationService = DirectCast(workspace.Services.GetService(Of INotificationService)(), INotificationServiceCallback) notificationService.NotificationCallback = Sub(message, title, severity) actualSeverity = severity editHandler.Apply( workspace, workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), Await actions.First().NestedCodeActions.First().GetOperationsAsync(CancellationToken.None), "unused", New ProgressTracker(), CancellationToken.None) ' CodeAction should be rejected Assert.Equal(NotificationSeverity.Error, actualSeverity) Assert.Equal(" class C { void M() { var z = 5 + 5; var q = xyz; } int xyz; }", textBuffer.CurrentSnapshot.GetText()) ' Rename should still be active Await VerifyTagsAreCorrect(workspace, "xyz") textBuffer.Insert(caretPosition + 2, "q") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "xyzq") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof([|M|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof(M).ToString(); } void M(int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads_WithRenameOverloadsOption(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|$$M|]() { nameof([|M|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "M", "Sa", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1142095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1142095")> Public Async Function RenameCommitsWhenDebuggingStarts(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") ' Make sure the RenameService's ActiveSession is still there Dim renameService = workspace.GetService(Of IInlineRenameService)() Assert.NotNull(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") ' Simulate starting a debugging session Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService) debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run) ' Ensure the rename was committed Assert.Null(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1142095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1142095")> Public Async Function RenameCommitsWhenExitingDebuggingBreakMode(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") ' Make sure the RenameService's ActiveSession is still there Dim renameService = workspace.GetService(Of IInlineRenameService)() Assert.NotNull(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") ' Simulate ending break mode in the debugger (by stepping or continuing) Dim debuggingService = workspace.Services.GetService(Of IDebuggingWorkspaceService) debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run) ' Ensure the rename was committed Assert.Null(renameService.ActiveSession) Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3316, "https://github.com/dotnet/roslyn/issues/3316")> Public Async Function InvalidInvocationExpression(host As RenameTestHost) As Task ' Everything on the last line of main is parsed as a single invocation expression ' with CType(...) as the receiver and everything else as arguments. ' Rename doesn't expect to see CType as the receiver of an invocation. Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Module1 Sub Main() Dim [|$$p|] As IEnumerable(Of Integer) = {1, 2, 3} Dim linked = Enumerable.Aggregate(Of Global.&lt;anonymous type:head As Global.System.Int32, tail As Global.System.Object&gt;)( CType([|p|], IEnumerable(Of Integer)), Nothing, Function(total, curr) Nothing) End Sub End Module </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "q") session.Commit() Await VerifyTagsAreCorrect(workspace, "qp") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(2445, "https://github.com/dotnet/roslyn/issues/2445")> Public Async Function InvalidExpansionTarget(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> int x; x = 2; void [|$$M|]() { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "x") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(9117, "https://github.com/dotnet/roslyn/issues/9117")> Public Async Function VerifyVBRenameCrashDoesNotRepro(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class1 Public Property [|$$Field1|] As Integer End Class Public Class Class2 Public Shared Property DataSource As IEnumerable(Of Class1) Public ReadOnly Property Dict As IReadOnlyDictionary(Of Integer, IEnumerable(Of Class1)) = ( From data In DataSource Group By data.Field1 Into Group1 = Group ).ToDictionary( Function(group) group.Field1, Function(group) group.Group1) End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "xield1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(14554, "https://github.com/dotnet/roslyn/issues/14554")> Public Sub VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub New(a As Action) End Sub Public ReadOnly Property Vm As C Public ReadOnly Property Crash As New C(Sub() Vm.Sav() End Sub) Public Function Sav$$() As Boolean Return False End Function Public Function Save() As Boolean Return False End Function End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' Ensure the rename doesn't crash textBuffer.Insert(caretPosition, "e") session.Commit() End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedForPartialType(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Goo|] { void Blah() { } } </Document> <Document> partial class Goo { void BlahBlah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeWithMultipleLocations, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedForPartialTypeWithSingleLocation(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Test1|] { void Blah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedWithMultipleTypesOnMatchingName(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { } } class Test2 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedWithMultipleTypes(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { } } class Test1 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeDoesNotMatchFileName, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyEnumKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum [|$$Test1|] { One, Two, Three } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyInterfaceKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface [|$$Test1|] { void Blah(); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyUnsupportedFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface Test1 { void [|$$Blah|](); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameNotAllowedForLinkedFiles(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) ' Disable document changes to make sure file rename is not supported. ' Linked workspace files will report that applying changes to document ' info is not allowed; this is intended to mimic that behavior ' and make sure inline rename works as intended. workspace.CanApplyChangeDocument = False Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "t") session.Commit() VerifyFileName(workspace, "test1") End Using End Sub <WpfTheory, WorkItem(36063, "https://github.com/dotnet/roslyn/issues/36063")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function EditBackToOriginalNameThenCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") textBuffer.Delete(New Span(caretPosition, "Bar".Length)) Dim committed = session.GetTestAccessor().CommitWorker(previewChanges:=False) Assert.False(committed) Await VerifyTagsAreCorrect(workspace, "Test1") End Using End Function <WpfTheory, WorkItem(44576, "https://github.com/dotnet/roslyn/issues/44576")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameFromOtherFile(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test1 { void Blah() { [|$$Test2|] t2 = new [|Test2|](); } } </Document> <Document Name="Test2.cs"> class Test2 { } </Document> </Project> </Workspace>, host) Dim docToRename = workspace.Documents.First(Function(doc) doc.Name = "Test2.cs") Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="Test2", renameTextPrefix:="Test2Changed", renameFile:=True, fileToRename:=docToRename.Id) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameConstructorReferencedInGlobalSuppression(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:[|C|].#ctor")] class [|C|] { public [|$$C|]() { } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "D") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithNoBody1(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a); class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithBody(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordConstructorCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g = new [|Goo|](1); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameExtendedProperty(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class C { void M() { _ = this is { Other.[|Goo|]: not null, Other.Other.[|Goo|]: not null, [|Goo|]: null } ; } public C [|$$Goo|] { get; set; } public C Other { get; set; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameInComment(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class [|$$MyClass|] { /// <summary> /// Initializes <see cref="MyClass"/>; /// </summary> MyClass() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) session.ApplyReplacementText("Example", True) session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInComments, True) session.Commit() Await VerifyTagsAreCorrect(workspace, "Example") End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ContextQuery/SyntaxTokenExtensions.vb
' 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. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Friend Module SyntaxTokenExtensions <Extension> Friend Function HasColonBeforePosition(token As SyntaxToken, position As Integer) As Boolean Do If token.TrailingTrivia.Any(Function(t) t.IsKind(SyntaxKind.ColonTrivia) AndAlso t.Span.End <= position) Then Return True End If token = token.GetNextToken(includeZeroWidth:=True) Loop While token.IsMissing Return False End Function Private Function CheckTrivia(triviaList As SyntaxTriviaList, position As Integer, ByRef checkForSecondEol As Boolean, ByRef allowsImplicitLineContinuation As Boolean) As Boolean For Each trivia In triviaList If trivia.IsKind(SyntaxKind.LineContinuationTrivia) AndAlso trivia.Span.End <= position Then checkForSecondEol = True allowsImplicitLineContinuation = False ElseIf trivia.IsKind(SyntaxKind.EndOfLineTrivia) AndAlso trivia.Span.End <= position Then If Not allowsImplicitLineContinuation Then If checkForSecondEol Then checkForSecondEol = False Else Return True End If End If allowsImplicitLineContinuation = False End If Next Return False End Function ''' <summary> ''' We need to check for EOL trivia not preceded by LineContinuation trivia. ''' ''' This is slightly complicated since we need to get TrailingTrivia from missing tokens ''' and then get LeadingTrivia for the next non-missing token. ''' ''' Note that this is even more complicated in the case that we're in structured trivia ''' because we might be part of the leading trivia to the next non-missing token. ''' </summary> <Extension> Friend Function HasNonContinuableEndOfLineBeforePosition(token As SyntaxToken, position As Integer, Optional checkForSecondEol As Boolean = False) As Boolean If token.FollowsBadEndDirective() Then Return False End If Dim allowsImplicitLineContinuation = token.Parent IsNot Nothing AndAlso SyntaxFacts.AllowsTrailingImplicitLineContinuation(token) Dim originalToken = token Do If CheckTrivia(token.TrailingTrivia, position, checkForSecondEol, allowsImplicitLineContinuation) Then Return True End If token = token.GetNextToken(includeZeroWidth:=True) Loop While token.IsMissing ' If our our original token was in structured trivia (such as preprocesser), it's entirely possible that the ' leading trivia of the next non-missing token might contain it. If that's the case, we don't want to check ' its leading trivia before it might have trivia that appear *before* the original token. ' ' Consider the following example: ' ' Class C ' ' #Region $$ ' End Class ' ' In the code above, the original token is "Region", but the leading trivia to the next non-missing token ("End") ' includes the structured trivia containing the original token plus the trivia before it. In that case, we don't ' want to check the leading trivia of the "End". If Not token.LeadingTrivia.Span.Contains(originalToken.Span) Then Return CheckTrivia(token.LeadingTrivia, position, checkForSecondEol, allowsImplicitLineContinuation) Else Return False End If End Function <Extension> Friend Function FollowsBadEndDirective(targetToken As SyntaxToken) As Boolean If targetToken.IsKind(SyntaxKind.HashToken) AndAlso targetToken.TrailingTrivia.Any(Function(t) If t.HasStructure Then Dim childTokens = t.GetStructure().ChildTokens() Return childTokens.Count() = 1 AndAlso childTokens.First().IsKind(SyntaxKind.EndKeyword) End If Return False End Function) Then Return targetToken.Parent.IsKind(SyntaxKind.BadDirectiveTrivia) End If Return targetToken.IsKind(SyntaxKind.EndKeyword) AndAlso targetToken.GetPreviousToken().IsKind(SyntaxKind.HashToken) AndAlso targetToken.GetPreviousToken().Parent.IsKind(SyntaxKind.BadDirectiveTrivia) End Function <Extension> Friend Function FollowsEndOfStatement(token As SyntaxToken, position As Integer) As Boolean Return token.HasColonBeforePosition(position) OrElse token.HasNonContinuableEndOfLineBeforePosition(position) End Function <Extension> Friend Function MustBeginNewStatement(token As SyntaxToken, position As Integer) As Boolean Return token.HasColonBeforePosition(position) OrElse token.HasNonContinuableEndOfLineBeforePosition(position, checkForSecondEol:=True) End Function <Extension> Friend Function IsMandatoryNamedParameterPosition(token As SyntaxToken) As Boolean If token.Kind() = SyntaxKind.CommaToken Then Dim argumentList = TryCast(token.Parent, ArgumentListSyntax) If argumentList Is Nothing Then Return False End If For Each n In argumentList.Arguments.GetWithSeparators() If n.IsToken AndAlso n.AsToken() = token Then Return False End If If n.IsNode AndAlso DirectCast(n.AsNode(), ArgumentSyntax).IsNamed Then Return True End If Next End If Return False End Function <Extension()> Friend Function IsModifier(token As SyntaxToken) As Boolean Select Case token.Kind Case SyntaxKind.AsyncKeyword, SyntaxKind.ConstKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.PublicKeyword, SyntaxKind.FriendKeyword, SyntaxKind.ShadowsKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.MustInheritKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.NarrowingKeyword, SyntaxKind.WideningKeyword, SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.OverloadsKeyword, SyntaxKind.OverridableKeyword, SyntaxKind.OverridesKeyword, SyntaxKind.PartialKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.WriteOnlyKeyword, SyntaxKind.SharedKeyword, SyntaxKind.WithEventsKeyword, SyntaxKind.CustomKeyword, SyntaxKind.IteratorKeyword Return True Case Else Return False End Select End Function End Module End Namespace
' 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. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Friend Module SyntaxTokenExtensions <Extension> Friend Function HasColonBeforePosition(token As SyntaxToken, position As Integer) As Boolean Do If token.TrailingTrivia.Any(Function(t) t.IsKind(SyntaxKind.ColonTrivia) AndAlso t.Span.End <= position) Then Return True End If token = token.GetNextToken(includeZeroWidth:=True) Loop While token.IsMissing Return False End Function Private Function CheckTrivia(triviaList As SyntaxTriviaList, position As Integer, ByRef checkForSecondEol As Boolean, ByRef allowsImplicitLineContinuation As Boolean) As Boolean For Each trivia In triviaList If trivia.IsKind(SyntaxKind.LineContinuationTrivia) AndAlso trivia.Span.End <= position Then checkForSecondEol = True allowsImplicitLineContinuation = False ElseIf trivia.IsKind(SyntaxKind.EndOfLineTrivia) AndAlso trivia.Span.End <= position Then If Not allowsImplicitLineContinuation Then If checkForSecondEol Then checkForSecondEol = False Else Return True End If End If allowsImplicitLineContinuation = False End If Next Return False End Function ''' <summary> ''' We need to check for EOL trivia not preceded by LineContinuation trivia. ''' ''' This is slightly complicated since we need to get TrailingTrivia from missing tokens ''' and then get LeadingTrivia for the next non-missing token. ''' ''' Note that this is even more complicated in the case that we're in structured trivia ''' because we might be part of the leading trivia to the next non-missing token. ''' </summary> <Extension> Friend Function HasNonContinuableEndOfLineBeforePosition(token As SyntaxToken, position As Integer, Optional checkForSecondEol As Boolean = False) As Boolean If token.FollowsBadEndDirective() Then Return False End If Dim allowsImplicitLineContinuation = token.Parent IsNot Nothing AndAlso SyntaxFacts.AllowsTrailingImplicitLineContinuation(token) Dim originalToken = token Do If CheckTrivia(token.TrailingTrivia, position, checkForSecondEol, allowsImplicitLineContinuation) Then Return True End If token = token.GetNextToken(includeZeroWidth:=True) Loop While token.IsMissing ' If our our original token was in structured trivia (such as preprocesser), it's entirely possible that the ' leading trivia of the next non-missing token might contain it. If that's the case, we don't want to check ' its leading trivia before it might have trivia that appear *before* the original token. ' ' Consider the following example: ' ' Class C ' ' #Region $$ ' End Class ' ' In the code above, the original token is "Region", but the leading trivia to the next non-missing token ("End") ' includes the structured trivia containing the original token plus the trivia before it. In that case, we don't ' want to check the leading trivia of the "End". If Not token.LeadingTrivia.Span.Contains(originalToken.Span) Then Return CheckTrivia(token.LeadingTrivia, position, checkForSecondEol, allowsImplicitLineContinuation) Else Return False End If End Function <Extension> Friend Function FollowsBadEndDirective(targetToken As SyntaxToken) As Boolean If targetToken.IsKind(SyntaxKind.HashToken) AndAlso targetToken.TrailingTrivia.Any(Function(t) If t.HasStructure Then Dim childTokens = t.GetStructure().ChildTokens() Return childTokens.Count() = 1 AndAlso childTokens.First().IsKind(SyntaxKind.EndKeyword) End If Return False End Function) Then Return targetToken.Parent.IsKind(SyntaxKind.BadDirectiveTrivia) End If Return targetToken.IsKind(SyntaxKind.EndKeyword) AndAlso targetToken.GetPreviousToken().IsKind(SyntaxKind.HashToken) AndAlso targetToken.GetPreviousToken().Parent.IsKind(SyntaxKind.BadDirectiveTrivia) End Function <Extension> Friend Function FollowsEndOfStatement(token As SyntaxToken, position As Integer) As Boolean Return token.HasColonBeforePosition(position) OrElse token.HasNonContinuableEndOfLineBeforePosition(position) End Function <Extension> Friend Function MustBeginNewStatement(token As SyntaxToken, position As Integer) As Boolean Return token.HasColonBeforePosition(position) OrElse token.HasNonContinuableEndOfLineBeforePosition(position, checkForSecondEol:=True) End Function <Extension> Friend Function IsMandatoryNamedParameterPosition(token As SyntaxToken) As Boolean If token.Kind() = SyntaxKind.CommaToken Then Dim argumentList = TryCast(token.Parent, ArgumentListSyntax) If argumentList Is Nothing Then Return False End If For Each n In argumentList.Arguments.GetWithSeparators() If n.IsToken AndAlso n.AsToken() = token Then Return False End If If n.IsNode AndAlso DirectCast(n.AsNode(), ArgumentSyntax).IsNamed Then Return True End If Next End If Return False End Function <Extension()> Friend Function IsModifier(token As SyntaxToken) As Boolean Select Case token.Kind Case SyntaxKind.AsyncKeyword, SyntaxKind.ConstKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.PublicKeyword, SyntaxKind.FriendKeyword, SyntaxKind.ShadowsKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.MustInheritKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.NarrowingKeyword, SyntaxKind.WideningKeyword, SyntaxKind.NotInheritableKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.OverloadsKeyword, SyntaxKind.OverridableKeyword, SyntaxKind.OverridesKeyword, SyntaxKind.PartialKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.WriteOnlyKeyword, SyntaxKind.SharedKeyword, SyntaxKind.WithEventsKeyword, SyntaxKind.CustomKeyword, SyntaxKind.IteratorKeyword Return True Case Else Return False End Select End Function End Module End Namespace
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./docs/compilers/Design/Parser.md
Parser Design Guidelines ======================== This document describes design guidelines for the Roslyn parsers. These are not hard rules that cannot be violated. Use good judgment. It is acceptable to vary from the guidelines when there are reasons that outweigh their benefits. ![image](https://i0.wp.com/media.tumblr.com/tumblr_lzwm2hKMGx1qhkwbs.gif) The parsers do not currently comply with these guidelines, even in places where there is no good reason not to. The guidelines were written after the parsers. We expect to refactor the parsers opportunistically to comply with these guidelines, particularly when there are concrete benefit from doing so. Designing the syntax model (data model for the syntax tree) for new features is currently outside the scope of these guidelines. #### **DO** have the parser accept input text that complies with the syntax model The syntax model defines the contract between syntax and semantic analysis. If the parser can build a meaningful syntax tree for a sequence of input tokens, then it should be left to semantic analysis to report when that tree is not semantically valid. The most important diagnostics to report from the parser are "missing token" and "unexpected token". There may be reasons to violate this rule. For example, the syntax model does not have a concept of precedence, but the parser uses precedence to decide how to assemble the tree. Precedence errors are therefore reported in the parser. #### **DO NOT** use ambient context to direct the behavior of the parser The parser should, as much as possible, be context-free. Use context where needed only to resolve language ambiguities. For example, in contexts where both a type and an expression are permitted, but a type is preferred, (such as the right-hand-side of `is`) we parse `X.Y` as a type. But in contexts where both are permitted, but it is to be treated as a type only if followed by an identifier (such as following `case`), we use look-ahead to decide which kind of tree to build. Try to minimize the amount of context used to make parsing decisions, as that will improve the quality of incremental parsing. There may be reasons to violate this rule, for example where the language is specified to be sensitive to context. For example, `await` is treated as a keyword if the enclosing method has the `async` modifier. #### Examples Here are some examples of places where we might change the parser toward satisfying these guidelines, and the problems that may solve: 1. 100l : warning: use `L` for long literals It may seem a small thing to produce this warning in the parser, but it interferes with incremental parsing. The incremental parser will not reuse a node that has diagnostics. As a consequence, even the presence of this helpful warning in code can reduce the performance of the parser as the user types in that source. That reduced performance may mean that the editor will not appear as responsive. By moving this warning out of the parser and into semantic analysis, the IDE can be more responsive during typing. 1. Member parsing The syntax model represents constructors and methods using separate nodes. When a declaration of the form `public M() {}` is seen, the parser checks the name of the function against the name of the enclosing type to decide whether it should represent it as a constructor, or as a method with a missing type. In this case the name of the enclosing type is a form of *ambient context* that affects the behavior of the compiler. By treating such as declaration as a constructor in the syntax model, and checking the name in semantic analysis, it becomes possible to expose a context-free public API for parsing a member declaration. See https://github.com/dotnet/roslyn/issues/367 for a feature request that we have been unable to do because of this problem.
Parser Design Guidelines ======================== This document describes design guidelines for the Roslyn parsers. These are not hard rules that cannot be violated. Use good judgment. It is acceptable to vary from the guidelines when there are reasons that outweigh their benefits. ![image](https://i0.wp.com/media.tumblr.com/tumblr_lzwm2hKMGx1qhkwbs.gif) The parsers do not currently comply with these guidelines, even in places where there is no good reason not to. The guidelines were written after the parsers. We expect to refactor the parsers opportunistically to comply with these guidelines, particularly when there are concrete benefit from doing so. Designing the syntax model (data model for the syntax tree) for new features is currently outside the scope of these guidelines. #### **DO** have the parser accept input text that complies with the syntax model The syntax model defines the contract between syntax and semantic analysis. If the parser can build a meaningful syntax tree for a sequence of input tokens, then it should be left to semantic analysis to report when that tree is not semantically valid. The most important diagnostics to report from the parser are "missing token" and "unexpected token". There may be reasons to violate this rule. For example, the syntax model does not have a concept of precedence, but the parser uses precedence to decide how to assemble the tree. Precedence errors are therefore reported in the parser. #### **DO NOT** use ambient context to direct the behavior of the parser The parser should, as much as possible, be context-free. Use context where needed only to resolve language ambiguities. For example, in contexts where both a type and an expression are permitted, but a type is preferred, (such as the right-hand-side of `is`) we parse `X.Y` as a type. But in contexts where both are permitted, but it is to be treated as a type only if followed by an identifier (such as following `case`), we use look-ahead to decide which kind of tree to build. Try to minimize the amount of context used to make parsing decisions, as that will improve the quality of incremental parsing. There may be reasons to violate this rule, for example where the language is specified to be sensitive to context. For example, `await` is treated as a keyword if the enclosing method has the `async` modifier. #### Examples Here are some examples of places where we might change the parser toward satisfying these guidelines, and the problems that may solve: 1. 100l : warning: use `L` for long literals It may seem a small thing to produce this warning in the parser, but it interferes with incremental parsing. The incremental parser will not reuse a node that has diagnostics. As a consequence, even the presence of this helpful warning in code can reduce the performance of the parser as the user types in that source. That reduced performance may mean that the editor will not appear as responsive. By moving this warning out of the parser and into semantic analysis, the IDE can be more responsive during typing. 1. Member parsing The syntax model represents constructors and methods using separate nodes. When a declaration of the form `public M() {}` is seen, the parser checks the name of the function against the name of the enclosing type to decide whether it should represent it as a constructor, or as a method with a missing type. In this case the name of the enclosing type is a form of *ambient context* that affects the behavior of the compiler. By treating such as declaration as a constructor in the syntax model, and checking the name in semantic analysis, it becomes possible to expose a context-free public API for parsing a member declaration. See https://github.com/dotnet/roslyn/issues/367 for a feature request that we have been unable to do because of this problem.
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/VisualStudio/Core/Impl/CodeModel/Collections/InheritsImplementsCollection.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 System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class InheritsImplementsCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) { var collection = new InheritsImplementsCollection(state, parent, fileCodeModel, nodeKey); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNodeKey _nodeKey; private InheritsImplementsCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private SyntaxNode LookupNode() => FileCodeModel.LookupNode(_nodeKey); internal override Snapshot CreateSnapshot() { var node = LookupNode(); var parentElement = (AbstractCodeElement)this.Parent; var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance(); nodesBuilder.AddRange(CodeModelService.GetInheritsNodes(node)); nodesBuilder.AddRange(CodeModelService.GetImplementsNodes(node)); return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement, nodesBuilder.ToImmutableAndFree()); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var currentIndex = 0; // Inherits statements var inheritsNodes = CodeModelService.GetInheritsNodes(node); var inheritsNodeCount = inheritsNodes.Count(); if (index < currentIndex + inheritsNodeCount) { var child = inheritsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } currentIndex += inheritsNodeCount; // Implements statements var implementsNodes = CodeModelService.GetImplementsNodes(node); var implementsNodeCount = implementsNodes.Count(); if (index < currentIndex + implementsNodeCount) { var child = implementsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); // Inherits statements foreach (var child in CodeModelService.GetInheritsNodes(node)) { CodeModelService.GetInheritsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } // Implements statements foreach (var child in CodeModelService.GetImplementsNodes(node)) { CodeModelService.GetImplementsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetInheritsNodes(node).Count() + CodeModelService.GetImplementsNodes(node).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. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class InheritsImplementsCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) { var collection = new InheritsImplementsCollection(state, parent, fileCodeModel, nodeKey); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNodeKey _nodeKey; private InheritsImplementsCollection( CodeModelState state, object parent, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey) : base(state, parent) { Debug.Assert(fileCodeModel != null); _fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel); _nodeKey = nodeKey; } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private SyntaxNode LookupNode() => FileCodeModel.LookupNode(_nodeKey); internal override Snapshot CreateSnapshot() { var node = LookupNode(); var parentElement = (AbstractCodeElement)this.Parent; var nodesBuilder = ArrayBuilder<SyntaxNode>.GetInstance(); nodesBuilder.AddRange(CodeModelService.GetInheritsNodes(node)); nodesBuilder.AddRange(CodeModelService.GetImplementsNodes(node)); return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement, nodesBuilder.ToImmutableAndFree()); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var node = LookupNode(); var currentIndex = 0; // Inherits statements var inheritsNodes = CodeModelService.GetInheritsNodes(node); var inheritsNodeCount = inheritsNodes.Count(); if (index < currentIndex + inheritsNodeCount) { var child = inheritsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } currentIndex += inheritsNodeCount; // Implements statements var implementsNodes = CodeModelService.GetImplementsNodes(node); var implementsNodeCount = implementsNodes.Count(); if (index < currentIndex + implementsNodeCount) { var child = implementsNodes.ElementAt(index - currentIndex); element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var node = LookupNode(); // Inherits statements foreach (var child in CodeModelService.GetInheritsNodes(node)) { CodeModelService.GetInheritsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } // Implements statements foreach (var child in CodeModelService.GetImplementsNodes(node)) { CodeModelService.GetImplementsNamespaceAndOrdinal(node, child, out var childName, out var ordinal); if (childName == name) { element = FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(child); return true; } } element = null; return false; } public override int Count { get { var node = LookupNode(); return CodeModelService.GetInheritsNodes(node).Count() + CodeModelService.GetImplementsNodes(node).Count(); } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/MSBuildTask/xlf/ErrorString.it.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="it" original="../ErrorString.resx"> <body> <trans-unit id="Compiler_UnexpectedException"> <source>MSB3883: Unexpected exception: </source> <target state="translated">MSB3883: Eccezione imprevista: </target> <note>{StrBegin="MSB3883: "}</note> </trans-unit> <trans-unit id="Csc_AssemblyAliasContainsIllegalCharacters"> <source>MSB3053: The assembly alias "{1}" on reference "{0}" contains illegal characters.</source> <target state="translated">MSB3053: l'alias dell'assembly "{1}" nel riferimento "{0}" contiene caratteri non ammessi.</target> <note>{StrBegin="MSB3053: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameter"> <source>MSB3051: The parameter to the compiler is invalid. {0}</source> <target state="translated">MSB3051: parametro del compilatore non valido. {0}</target> <note>{StrBegin="MSB3051: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameterWarning"> <source>MSB3052: The parameter to the compiler is invalid, '{0}{1}' will be ignored.</source> <target state="translated">MSB3052: il parametro per il compilatore non è valido. '{0}{1}' verrà ignorato.</target> <note>{StrBegin="MSB3052: "}</note> </trans-unit> <trans-unit id="General_CannotConvertStringToBool"> <source>The string "{0}" cannot be converted to a boolean (true/false) value.</source> <target state="translated">Non è possibile convertire la stringa "{0}" in un valore booleano (true/false).</target> <note /> </trans-unit> <trans-unit id="General_CouldNotSetHostObjectParameter"> <source>MSB3081: A problem occurred while trying to set the "{0}" parameter for the IDE's in-process compiler. {1}</source> <target state="translated">MSB3081: si è verificato un problema durante il tentativo di impostare il parametro "{0}" per il compilatore in-process dell'IDE. {1}</target> <note>{StrBegin="MSB3081: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupported"> <source>MSB3105: The item "{0}" was specified more than once in the "{1}" parameter. Duplicate items are not supported by the "{1}" parameter.</source> <target state="translated">MSB3105: l'elemento "{0}" è stato specificato più di una volta nel parametro "{1}", ma il parametro "{1}" non supporta gli elementi duplicati.</target> <note>{StrBegin="MSB3105: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupportedWithMetadata"> <source>MSB3083: The item "{0}" was specified more than once in the "{1}" parameter and both items had the same value "{2}" for the "{3}" metadata. Duplicate items are not supported by the "{1}" parameter unless they have different values for the "{3}" metadata.</source> <target state="translated">MSB3083: l'elemento "{0}" è stato specificato più di una volta nel parametro "{1}" ed entrambi gli elementi hanno lo stesso valore "{2}" per i metadati di "{3}". Il parametro "{1}" non supporta gli elementi duplicati a meno che non includano valori diversi per i metadati di "{3}".</target> <note>{StrBegin="MSB3083: "}</note> </trans-unit> <trans-unit id="General_ExpectedFileMissing"> <source>Expected file "{0}" does not exist.</source> <target state="translated">Il file previsto "{0}" non esiste.</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SkippingCopy1"> <source>Reference assembly "{0}" already has latest information. Leaving it untouched.</source> <target state="translated">Le informazioni nell'assembly di riferimento "{0}" sono già le più recenti. Non verranno modificate.</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SourceNotRef1"> <source>Could not extract the MVID from "{0}". Are you sure it is a reference assembly?</source> <target state="translated">Non è stato possibile estrarre il MVID da "{0}". Si è sicuri che si tratti di un assembly di riferimento?</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadSource3"> <source>Failed to check the content hash of the source ref assembly '{0}': {1} {2}</source> <target state="translated">Non è stato possibile verificare l'hash del contenuto dell'assembly di riferimento di origine '{0}': {1} {2}</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadDestination1"> <source>Failed to check the content hash of the destination ref assembly '{0}'. It will be overwritten.</source> <target state="translated">Non è stato possibile verificare l'hash del contenuto dell'assembly di riferimento di destinazione '{0}'. Verrà sovrascritto.</target> <note /> </trans-unit> <trans-unit id="General_ToolFileNotFound"> <source>MSB3082: Task failed because "{0}" was not found.</source> <target state="translated">MSB3082: l'attività non è riuscita perché "{0}" non è stato trovato.</target> <note>{StrBegin="MSB3082: "}</note> </trans-unit> <trans-unit id="General_IncorrectHostObject"> <source>MSB3087: An incompatible host object was passed into the "{0}" task. The host object for this task must implement the "{1}" interface.</source> <target state="translated">MSB3087: all'attività "{0}" è stato passato un oggetto host incompatibile. L'oggetto host di questa attività deve implementare l'interfaccia "{1}".</target> <note>{StrBegin="MSB3087: "}</note> </trans-unit> <trans-unit id="General_InvalidAttributeMetadata"> <source>Item "{0}" has attribute "{1}" with value "{2}" that could not be converted to "{3}".</source> <target state="translated">L'elemento "{0}" contiene l'attributo "{1}" con valore "{2}" che non è stato possibile convertire in "{3}".</target> <note /> </trans-unit> <trans-unit id="General_ParameterUnsupportedOnHostCompiler"> <source>The IDE's in-process compiler does not support the specified values for the "{0}" parameter. Therefore, this task will fallback to using the command-line compiler.</source> <target state="translated">Il compilatore in-process dell'IDE non supporta i valori specificati per il parametro "{0}", di conseguenza per questa attività verrà usato in sostituzione il compilatore da riga di comando.</target> <note /> </trans-unit> <trans-unit id="General_ReferenceDoesNotExist"> <source>MSB3104: The referenced assembly "{0}" was not found. If this assembly is produced by another one of your projects, please make sure to build that project before building this one.</source> <target state="translated">MSB3104: il modello "{0}" a cui si fa riferimento non è stato trovato. Se l'assembly è prodotto da un altro progetto, assicurarsi di compilare tale progetto prima di compilare quello corrente.</target> <note>{StrBegin="MSB3104: "}</note> </trans-unit> <trans-unit id="General_UnableToReadFile"> <source>File "{0}" could not be read: {1}</source> <target state="translated">Non è stato possibile leggere il file "{0}": {1}</target> <note /> </trans-unit> <trans-unit id="ImplicitlySkipAnalyzersMessage"> <source>Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</source> <target state="new">Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</target> <note /> </trans-unit> <trans-unit id="SharedCompilationFallback"> <source>Shared compilation failed; falling back to tool: {0}</source> <target state="translated">La compilazione condivisa non è riuscita. Verrà eseguito il fallback allo strumento: {0}</target> <note /> </trans-unit> <trans-unit id="UsingSharedCompilation"> <source>Using shared compilation with compiler from directory: {0}</source> <target state="translated">Verrà usata la compilazione condivisa con il compilatore della directory: {0}</target> <note /> </trans-unit> <trans-unit id="Vbc_EnumParameterHasInvalidValue"> <source>MSB3401: "{1}" is an invalid value for the "{0}" parameter. The valid values are: {2}</source> <target state="translated">MSB3401: "{1}" è un valore non valido per il parametro "{0}". I valori validi sono: {2}</target> <note>{StrBegin="MSB3401: "}</note> </trans-unit> <trans-unit id="Vbc_ParameterHasInvalidValue"> <source>"{1}" is an invalid value for the "{0}" parameter.</source> <target state="translated">"{1}" non è un valore valido per il parametro "{0}".</target> <note /> </trans-unit> <trans-unit id="Vbc_RenamePDB"> <source>MSB3402: There was an error creating the pdb file "{0}". {1}</source> <target state="translated">MSB3402: si è verificato un errore durante la creazione del file PDB "{0}". {1}</target> <note>{StrBegin="MSB3402: "}</note> </trans-unit> <trans-unit id="MapSourceRoots.ContainsDuplicate"> <source>{0} contains duplicate items '{1}' with conflicting metadata '{2}': '{3}' and '{4}'</source> <target state="translated">{0} contiene elementi duplicati '{1}' con metadati in conflitto '{2}': '{3}' e '{4}'</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.PathMustEndWithSlashOrBackslash"> <source>{0} paths are required to end with a slash or backslash: '{1}'</source> <target state="translated">{0} percorsi devono terminare con una barra o una barra rovesciata: '{1}'</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoTopLevelSourceRoot"> <source>{0} items must include at least one top-level (not nested) item when {1} is true</source> <target state="translated">{0} elementi devono includere almeno un elemento di primo livello (non annidato) quando {1} è true</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoSuchTopLevelSourceRoot"> <source>The value of {0} not found in {1} items, or the corresponding item is not a top-level source root: '{2}'</source> <target state="translated">Il valore di {0} non è stato trovato negli elementi {1} oppure l'elemento corrispondente non è una radice di origine di primo livello: '{2}'</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="it" original="../ErrorString.resx"> <body> <trans-unit id="Compiler_UnexpectedException"> <source>MSB3883: Unexpected exception: </source> <target state="translated">MSB3883: Eccezione imprevista: </target> <note>{StrBegin="MSB3883: "}</note> </trans-unit> <trans-unit id="Csc_AssemblyAliasContainsIllegalCharacters"> <source>MSB3053: The assembly alias "{1}" on reference "{0}" contains illegal characters.</source> <target state="translated">MSB3053: l'alias dell'assembly "{1}" nel riferimento "{0}" contiene caratteri non ammessi.</target> <note>{StrBegin="MSB3053: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameter"> <source>MSB3051: The parameter to the compiler is invalid. {0}</source> <target state="translated">MSB3051: parametro del compilatore non valido. {0}</target> <note>{StrBegin="MSB3051: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameterWarning"> <source>MSB3052: The parameter to the compiler is invalid, '{0}{1}' will be ignored.</source> <target state="translated">MSB3052: il parametro per il compilatore non è valido. '{0}{1}' verrà ignorato.</target> <note>{StrBegin="MSB3052: "}</note> </trans-unit> <trans-unit id="General_CannotConvertStringToBool"> <source>The string "{0}" cannot be converted to a boolean (true/false) value.</source> <target state="translated">Non è possibile convertire la stringa "{0}" in un valore booleano (true/false).</target> <note /> </trans-unit> <trans-unit id="General_CouldNotSetHostObjectParameter"> <source>MSB3081: A problem occurred while trying to set the "{0}" parameter for the IDE's in-process compiler. {1}</source> <target state="translated">MSB3081: si è verificato un problema durante il tentativo di impostare il parametro "{0}" per il compilatore in-process dell'IDE. {1}</target> <note>{StrBegin="MSB3081: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupported"> <source>MSB3105: The item "{0}" was specified more than once in the "{1}" parameter. Duplicate items are not supported by the "{1}" parameter.</source> <target state="translated">MSB3105: l'elemento "{0}" è stato specificato più di una volta nel parametro "{1}", ma il parametro "{1}" non supporta gli elementi duplicati.</target> <note>{StrBegin="MSB3105: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupportedWithMetadata"> <source>MSB3083: The item "{0}" was specified more than once in the "{1}" parameter and both items had the same value "{2}" for the "{3}" metadata. Duplicate items are not supported by the "{1}" parameter unless they have different values for the "{3}" metadata.</source> <target state="translated">MSB3083: l'elemento "{0}" è stato specificato più di una volta nel parametro "{1}" ed entrambi gli elementi hanno lo stesso valore "{2}" per i metadati di "{3}". Il parametro "{1}" non supporta gli elementi duplicati a meno che non includano valori diversi per i metadati di "{3}".</target> <note>{StrBegin="MSB3083: "}</note> </trans-unit> <trans-unit id="General_ExpectedFileMissing"> <source>Expected file "{0}" does not exist.</source> <target state="translated">Il file previsto "{0}" non esiste.</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SkippingCopy1"> <source>Reference assembly "{0}" already has latest information. Leaving it untouched.</source> <target state="translated">Le informazioni nell'assembly di riferimento "{0}" sono già le più recenti. Non verranno modificate.</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SourceNotRef1"> <source>Could not extract the MVID from "{0}". Are you sure it is a reference assembly?</source> <target state="translated">Non è stato possibile estrarre il MVID da "{0}". Si è sicuri che si tratti di un assembly di riferimento?</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadSource3"> <source>Failed to check the content hash of the source ref assembly '{0}': {1} {2}</source> <target state="translated">Non è stato possibile verificare l'hash del contenuto dell'assembly di riferimento di origine '{0}': {1} {2}</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadDestination1"> <source>Failed to check the content hash of the destination ref assembly '{0}'. It will be overwritten.</source> <target state="translated">Non è stato possibile verificare l'hash del contenuto dell'assembly di riferimento di destinazione '{0}'. Verrà sovrascritto.</target> <note /> </trans-unit> <trans-unit id="General_ToolFileNotFound"> <source>MSB3082: Task failed because "{0}" was not found.</source> <target state="translated">MSB3082: l'attività non è riuscita perché "{0}" non è stato trovato.</target> <note>{StrBegin="MSB3082: "}</note> </trans-unit> <trans-unit id="General_IncorrectHostObject"> <source>MSB3087: An incompatible host object was passed into the "{0}" task. The host object for this task must implement the "{1}" interface.</source> <target state="translated">MSB3087: all'attività "{0}" è stato passato un oggetto host incompatibile. L'oggetto host di questa attività deve implementare l'interfaccia "{1}".</target> <note>{StrBegin="MSB3087: "}</note> </trans-unit> <trans-unit id="General_InvalidAttributeMetadata"> <source>Item "{0}" has attribute "{1}" with value "{2}" that could not be converted to "{3}".</source> <target state="translated">L'elemento "{0}" contiene l'attributo "{1}" con valore "{2}" che non è stato possibile convertire in "{3}".</target> <note /> </trans-unit> <trans-unit id="General_ParameterUnsupportedOnHostCompiler"> <source>The IDE's in-process compiler does not support the specified values for the "{0}" parameter. Therefore, this task will fallback to using the command-line compiler.</source> <target state="translated">Il compilatore in-process dell'IDE non supporta i valori specificati per il parametro "{0}", di conseguenza per questa attività verrà usato in sostituzione il compilatore da riga di comando.</target> <note /> </trans-unit> <trans-unit id="General_ReferenceDoesNotExist"> <source>MSB3104: The referenced assembly "{0}" was not found. If this assembly is produced by another one of your projects, please make sure to build that project before building this one.</source> <target state="translated">MSB3104: il modello "{0}" a cui si fa riferimento non è stato trovato. Se l'assembly è prodotto da un altro progetto, assicurarsi di compilare tale progetto prima di compilare quello corrente.</target> <note>{StrBegin="MSB3104: "}</note> </trans-unit> <trans-unit id="General_UnableToReadFile"> <source>File "{0}" could not be read: {1}</source> <target state="translated">Non è stato possibile leggere il file "{0}": {1}</target> <note /> </trans-unit> <trans-unit id="ImplicitlySkipAnalyzersMessage"> <source>Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</source> <target state="new">Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</target> <note /> </trans-unit> <trans-unit id="SharedCompilationFallback"> <source>Shared compilation failed; falling back to tool: {0}</source> <target state="translated">La compilazione condivisa non è riuscita. Verrà eseguito il fallback allo strumento: {0}</target> <note /> </trans-unit> <trans-unit id="UsingSharedCompilation"> <source>Using shared compilation with compiler from directory: {0}</source> <target state="translated">Verrà usata la compilazione condivisa con il compilatore della directory: {0}</target> <note /> </trans-unit> <trans-unit id="Vbc_EnumParameterHasInvalidValue"> <source>MSB3401: "{1}" is an invalid value for the "{0}" parameter. The valid values are: {2}</source> <target state="translated">MSB3401: "{1}" è un valore non valido per il parametro "{0}". I valori validi sono: {2}</target> <note>{StrBegin="MSB3401: "}</note> </trans-unit> <trans-unit id="Vbc_ParameterHasInvalidValue"> <source>"{1}" is an invalid value for the "{0}" parameter.</source> <target state="translated">"{1}" non è un valore valido per il parametro "{0}".</target> <note /> </trans-unit> <trans-unit id="Vbc_RenamePDB"> <source>MSB3402: There was an error creating the pdb file "{0}". {1}</source> <target state="translated">MSB3402: si è verificato un errore durante la creazione del file PDB "{0}". {1}</target> <note>{StrBegin="MSB3402: "}</note> </trans-unit> <trans-unit id="MapSourceRoots.ContainsDuplicate"> <source>{0} contains duplicate items '{1}' with conflicting metadata '{2}': '{3}' and '{4}'</source> <target state="translated">{0} contiene elementi duplicati '{1}' con metadati in conflitto '{2}': '{3}' e '{4}'</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.PathMustEndWithSlashOrBackslash"> <source>{0} paths are required to end with a slash or backslash: '{1}'</source> <target state="translated">{0} percorsi devono terminare con una barra o una barra rovesciata: '{1}'</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoTopLevelSourceRoot"> <source>{0} items must include at least one top-level (not nested) item when {1} is true</source> <target state="translated">{0} elementi devono includere almeno un elemento di primo livello (non annidato) quando {1} è true</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoSuchTopLevelSourceRoot"> <source>The value of {0} not found in {1} items, or the corresponding item is not a top-level source root: '{2}'</source> <target state="translated">Il valore di {0} non è stato trovato negli elementi {1} oppure l'elemento corrispondente non è una radice di origine di primo livello: '{2}'</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/MSBuildTask/GenerateMSBuildEditorConfig.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.IO; using System.Linq; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// Transforms a set of MSBuild Properties and Metadata into a global analyzer config. /// </summary> /// <remarks> /// This task takes a set of items passed in via <see cref="MetadataItems"/> and <see cref="PropertyItems"/> and transforms /// them into a global analyzer config. /// /// <see cref="PropertyItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> is the property name /// and have a metadata value called <c>Value</c> that contains the evaluated value of the property. Each of the ] /// <see cref="PropertyItems"/> will be transformed into an <c>build_property.<em>ItemSpec</em> = <em>Value</em></c> entry in the /// global section of the generated config file. /// /// <see cref="MetadataItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> represents a file in the /// compilation source tree. It should have two metadata values: <c>ItemType</c> is the name of the MSBuild item that originally /// included the file (e.g. <c>Compile</c>, <c>AdditionalFile</c> etc.); <c>MetadataName</c> is expected to contain the name of /// another piece of metadata that should be retrieved and used as the output value in the file. It is expected that a given /// file can have multiple entries in the <see cref="MetadataItems" /> differing by its <c>ItemType</c>. /// /// Each of the <see cref="MetadataItems"/> will be transformed into a new section in the generated config file. The section /// header will be the full path of the item (generated via its<see cref="ITaskItem.ItemSpec"/>), and each section will have a /// set of <c>build_metadata.<em>ItemType</em>.<em>MetadataName</em> = <em>RetrievedMetadataValue</em></c>, one per <c>ItemType</c> /// /// The Microsoft.Managed.Core.targets calls this task with the collected results of the <c>AnalyzerProperty</c> and /// <c>AnalyzerItemMetadata</c> item groups. /// </remarks> public sealed class GenerateMSBuildEditorConfig : Task { /// <remarks> /// Although this task does its own writing to disk, this /// output parameter is here for testing purposes. /// </remarks> [Output] public string ConfigFileContents { get; set; } [Required] public ITaskItem[] MetadataItems { get; set; } [Required] public ITaskItem[] PropertyItems { get; set; } public ITaskItem FileName { get; set; } public GenerateMSBuildEditorConfig() { ConfigFileContents = string.Empty; MetadataItems = Array.Empty<ITaskItem>(); PropertyItems = Array.Empty<ITaskItem>(); FileName = new TaskItem(); } public override bool Execute() { StringBuilder builder = new StringBuilder(); // we always generate global configs builder.AppendLine("is_global = true"); // collect the properties into a global section foreach (var prop in PropertyItems) { builder.Append("build_property.") .Append(prop.ItemSpec) .Append(" = ") .AppendLine(prop.GetMetadata("Value")); } // group the metadata items by their full path var groupedItems = MetadataItems.GroupBy(i => NormalizeWithForwardSlash(i.GetMetadata("FullPath"))); foreach (var group in groupedItems) { // write the section for this item builder.AppendLine() .Append("["); EncodeString(builder, group.Key); builder.AppendLine("]"); foreach (var item in group) { string itemType = item.GetMetadata("ItemType"); string metadataName = item.GetMetadata("MetadataName"); if (!string.IsNullOrWhiteSpace(itemType) && !string.IsNullOrWhiteSpace(metadataName)) { builder.Append("build_metadata.") .Append(itemType) .Append(".") .Append(metadataName) .Append(" = ") .AppendLine(item.GetMetadata(metadataName)); } } } ConfigFileContents = builder.ToString(); return string.IsNullOrEmpty(FileName.ItemSpec) ? true : WriteMSBuildEditorConfig(); } internal bool WriteMSBuildEditorConfig() { try { var targetFileName = FileName.ItemSpec; if (File.Exists(targetFileName)) { string existingContents = File.ReadAllText(targetFileName); if (existingContents.Equals(ConfigFileContents)) { return true; } } var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); File.WriteAllText(targetFileName, ConfigFileContents, encoding); return true; } catch (IOException ex) { Log.LogErrorFromException(ex); return false; } } /// <remarks> /// Filenames with special characters like '#' and'{' get written /// into the section names in the resulting .editorconfig file. Later, /// when the file is parsed in configuration options these special /// characters are interpretted as invalid values and ignored by the /// processor. We encode the special characters in these strings /// before writing them here. /// </remarks> private static void EncodeString(StringBuilder builder, string value) { foreach (var c in value) { if (c is '*' or '?' or '{' or ',' or ';' or '}' or '[' or ']' or '#' or '!') { builder.Append("\\"); } builder.Append(c); } } /// <remarks> /// Equivalent to Roslyn.Utilities.PathUtilities.NormalizeWithForwardSlash /// Both methods should be kept in sync. /// </remarks> private static string NormalizeWithForwardSlash(string p) => PlatformInformation.IsUnix ? p : p.Replace('\\', '/'); } }
// 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.IO; using System.Linq; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// Transforms a set of MSBuild Properties and Metadata into a global analyzer config. /// </summary> /// <remarks> /// This task takes a set of items passed in via <see cref="MetadataItems"/> and <see cref="PropertyItems"/> and transforms /// them into a global analyzer config. /// /// <see cref="PropertyItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> is the property name /// and have a metadata value called <c>Value</c> that contains the evaluated value of the property. Each of the ] /// <see cref="PropertyItems"/> will be transformed into an <c>build_property.<em>ItemSpec</em> = <em>Value</em></c> entry in the /// global section of the generated config file. /// /// <see cref="MetadataItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> represents a file in the /// compilation source tree. It should have two metadata values: <c>ItemType</c> is the name of the MSBuild item that originally /// included the file (e.g. <c>Compile</c>, <c>AdditionalFile</c> etc.); <c>MetadataName</c> is expected to contain the name of /// another piece of metadata that should be retrieved and used as the output value in the file. It is expected that a given /// file can have multiple entries in the <see cref="MetadataItems" /> differing by its <c>ItemType</c>. /// /// Each of the <see cref="MetadataItems"/> will be transformed into a new section in the generated config file. The section /// header will be the full path of the item (generated via its<see cref="ITaskItem.ItemSpec"/>), and each section will have a /// set of <c>build_metadata.<em>ItemType</em>.<em>MetadataName</em> = <em>RetrievedMetadataValue</em></c>, one per <c>ItemType</c> /// /// The Microsoft.Managed.Core.targets calls this task with the collected results of the <c>AnalyzerProperty</c> and /// <c>AnalyzerItemMetadata</c> item groups. /// </remarks> public sealed class GenerateMSBuildEditorConfig : Task { /// <remarks> /// Although this task does its own writing to disk, this /// output parameter is here for testing purposes. /// </remarks> [Output] public string ConfigFileContents { get; set; } [Required] public ITaskItem[] MetadataItems { get; set; } [Required] public ITaskItem[] PropertyItems { get; set; } public ITaskItem FileName { get; set; } public GenerateMSBuildEditorConfig() { ConfigFileContents = string.Empty; MetadataItems = Array.Empty<ITaskItem>(); PropertyItems = Array.Empty<ITaskItem>(); FileName = new TaskItem(); } public override bool Execute() { StringBuilder builder = new StringBuilder(); // we always generate global configs builder.AppendLine("is_global = true"); // collect the properties into a global section foreach (var prop in PropertyItems) { builder.Append("build_property.") .Append(prop.ItemSpec) .Append(" = ") .AppendLine(prop.GetMetadata("Value")); } // group the metadata items by their full path var groupedItems = MetadataItems.GroupBy(i => NormalizeWithForwardSlash(i.GetMetadata("FullPath"))); foreach (var group in groupedItems) { // write the section for this item builder.AppendLine() .Append("["); EncodeString(builder, group.Key); builder.AppendLine("]"); foreach (var item in group) { string itemType = item.GetMetadata("ItemType"); string metadataName = item.GetMetadata("MetadataName"); if (!string.IsNullOrWhiteSpace(itemType) && !string.IsNullOrWhiteSpace(metadataName)) { builder.Append("build_metadata.") .Append(itemType) .Append(".") .Append(metadataName) .Append(" = ") .AppendLine(item.GetMetadata(metadataName)); } } } ConfigFileContents = builder.ToString(); return string.IsNullOrEmpty(FileName.ItemSpec) ? true : WriteMSBuildEditorConfig(); } internal bool WriteMSBuildEditorConfig() { try { var targetFileName = FileName.ItemSpec; if (File.Exists(targetFileName)) { string existingContents = File.ReadAllText(targetFileName); if (existingContents.Equals(ConfigFileContents)) { return true; } } var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); File.WriteAllText(targetFileName, ConfigFileContents, encoding); return true; } catch (IOException ex) { Log.LogErrorFromException(ex); return false; } } /// <remarks> /// Filenames with special characters like '#' and'{' get written /// into the section names in the resulting .editorconfig file. Later, /// when the file is parsed in configuration options these special /// characters are interpretted as invalid values and ignored by the /// processor. We encode the special characters in these strings /// before writing them here. /// </remarks> private static void EncodeString(StringBuilder builder, string value) { foreach (var c in value) { if (c is '*' or '?' or '{' or ',' or ';' or '}' or '[' or ']' or '#' or '!') { builder.Append("\\"); } builder.Append(c); } } /// <remarks> /// Equivalent to Roslyn.Utilities.PathUtilities.NormalizeWithForwardSlash /// Both methods should be kept in sync. /// </remarks> private static string NormalizeWithForwardSlash(string p) => PlatformInformation.IsUnix ? p : p.Replace('\\', '/'); } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Features/Core/Portable/ConvertAnonymousType/AbstractConvertAnonymousTypeToClassCodeRefactoringProvider.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertAnonymousType { internal abstract class AbstractConvertAnonymousTypeToClassCodeRefactoringProvider< TExpressionSyntax, TNameSyntax, TIdentifierNameSyntax, TObjectCreationExpressionSyntax, TAnonymousObjectCreationExpressionSyntax, TNamespaceDeclarationSyntax> : AbstractConvertAnonymousTypeCodeRefactoringProvider<TAnonymousObjectCreationExpressionSyntax> where TExpressionSyntax : SyntaxNode where TNameSyntax : TExpressionSyntax where TIdentifierNameSyntax : TNameSyntax where TObjectCreationExpressionSyntax : TExpressionSyntax where TAnonymousObjectCreationExpressionSyntax : TExpressionSyntax where TNamespaceDeclarationSyntax : SyntaxNode { protected abstract TObjectCreationExpressionSyntax CreateObjectCreationExpression(TNameSyntax nameNode, TAnonymousObjectCreationExpressionSyntax currentAnonymousObject); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; var (anonymousObject, anonymousType) = await TryGetAnonymousObjectAsync(document, textSpan, cancellationToken).ConfigureAwait(false); if (anonymousObject == null || anonymousType == null) return; // Check if the anonymous type actually references another anonymous type inside of it. // If it does, we can't convert this. There is no way to describe this anonymous type // in the concrete type we create. var containsAnonymousType = anonymousType.GetMembers() .OfType<IPropertySymbol>() .Any(p => p.Type.ContainsAnonymousType()); if (containsAnonymousType) return; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (syntaxFacts.SupportsRecord(anonymousObject.SyntaxTree.Options)) { context.RegisterRefactoring(new MyCodeAction( FeaturesResources.Convert_to_record, c => ConvertAsync(document, textSpan, isRecord: true, c)), anonymousObject.Span); } context.RegisterRefactoring(new MyCodeAction( FeaturesResources.Convert_to_class, c => ConvertAsync(document, textSpan, isRecord: false, c)), anonymousObject.Span); } private async Task<Document> ConvertAsync(Document document, TextSpan span, bool isRecord, CancellationToken cancellationToken) { var (anonymousObject, anonymousType) = await TryGetAnonymousObjectAsync(document, span, cancellationToken).ConfigureAwait(false); Debug.Assert(anonymousObject != null); Debug.Assert(anonymousType != null); var position = span.Start; var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Generate a unique name for the class we're creating. We'll also add a rename // annotation so the user can pick the right name for the type afterwards. var className = NameGenerator.GenerateUniqueName( isRecord ? "NewRecord" : "NewClass", n => semanticModel.LookupSymbols(position, name: n).IsEmpty); // First, create the set of properties this class will have based on the properties the // anonymous type has itself. Also, get a mapping of the original anonymous type's // properties to the new name we generated for it (if we converted camelCase to // PascalCase). var (properties, propertyMap) = GenerateProperties(document, anonymousType); // Next, generate the full class that will be used to replace all instances of this // anonymous type. var namedTypeSymbol = await GenerateFinalNamedTypeAsync( document, className, isRecord, properties, cancellationToken).ConfigureAwait(false); var generator = SyntaxGenerator.GetGenerator(document); var editor = new SyntaxEditor(root, generator); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var containingMember = anonymousObject.FirstAncestorOrSelf<SyntaxNode, ISyntaxFactsService>((node, syntaxFacts) => syntaxFacts.IsMethodLevelMember(node), syntaxFacts) ?? anonymousObject; // Next, go and update any references to these anonymous type properties to match // the new PascalCased name we've picked for the new properties that will go in // the named type. await ReplacePropertyReferencesAsync( document, editor, containingMember, propertyMap, cancellationToken).ConfigureAwait(false); // Next, go through and replace all matching anonymous types in this method with a call // to construct the new named type we've generated. await ReplaceMatchingAnonymousTypesAsync( document, editor, namedTypeSymbol, containingMember, anonymousObject, anonymousType, cancellationToken).ConfigureAwait(false); // Then, actually insert the new class in the appropriate container. var container = anonymousObject.GetAncestor<TNamespaceDeclarationSyntax>() ?? root; editor.ReplaceNode(container, (currentContainer, _) => { var codeGenService = document.GetRequiredLanguageService<ICodeGenerationService>(); var codeGenOptions = new CodeGenerationOptions( generateMembers: true, sortMembers: false, autoInsertionLocation: false, options: options, parseOptions: root.SyntaxTree.Options); return codeGenService.AddNamedType( currentContainer, namedTypeSymbol, codeGenOptions, cancellationToken); }); var updatedDocument = document.WithSyntaxRoot(editor.GetChangedRoot()); // Finally, format using the equals+getHashCode service so that our generated methods // follow any special formatting rules specific to them. var equalsAndGetHashCodeService = document.GetRequiredLanguageService<IGenerateEqualsAndGetHashCodeService>(); return await equalsAndGetHashCodeService.FormatDocumentAsync( updatedDocument, cancellationToken).ConfigureAwait(false); } private static async Task ReplacePropertyReferencesAsync( Document document, SyntaxEditor editor, SyntaxNode containingMember, ImmutableDictionary<IPropertySymbol, string> propertyMap, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var identifiers = containingMember.DescendantNodes().OfType<TIdentifierNameSyntax>(); foreach (var identifier in identifiers) { if (!syntaxFacts.IsNameOfSimpleMemberAccessExpression(identifier) && !syntaxFacts.IsNameOfMemberBindingExpression(identifier)) { continue; } if (semanticModel.GetSymbolInfo(identifier, cancellationToken).GetAnySymbol() is not IPropertySymbol symbol) continue; if (propertyMap.TryGetValue(symbol, out var newName)) { editor.ReplaceNode( identifier, (currentId, g) => g.IdentifierName(newName).WithTriviaFrom(currentId)); } } } private async Task ReplaceMatchingAnonymousTypesAsync( Document document, SyntaxEditor editor, INamedTypeSymbol classSymbol, SyntaxNode containingMember, TAnonymousObjectCreationExpressionSyntax creationNode, INamedTypeSymbol anonymousType, CancellationToken cancellationToken) { // When invoked we want to fixup all creations of the "same" anonymous type within the // containing method. We define same-ness as meaning "they have the type symbol". this // means both have the same member names, in the same order, with the same member types. // We fix all these up in the method because the user may be creating several instances // of this anonymous type in that method and then combining them in interesting ways // (i.e. checking them for equality, using them in collections, etc.). The language // guarantees within a method boundary that these will be the same type and can be used // together in this fashion. // // Note: we could consider expanding this in the future (potentially with another // lightbulb action). Specifically, we could look in the containing type and replace // any matches in any methods. var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var childCreationNodes = containingMember.DescendantNodesAndSelf() .OfType<TAnonymousObjectCreationExpressionSyntax>(); foreach (var childCreation in childCreationNodes) { var childType = semanticModel.GetTypeInfo(childCreation, cancellationToken).Type; if (childType == null) { Debug.Fail("We should always be able to get an anonymous type for any anonymous creation node."); continue; } if (anonymousType.Equals(childType)) ReplaceWithObjectCreation(editor, classSymbol, creationNode, childCreation); } } private void ReplaceWithObjectCreation( SyntaxEditor editor, INamedTypeSymbol classSymbol, TAnonymousObjectCreationExpressionSyntax startingCreationNode, TAnonymousObjectCreationExpressionSyntax childCreation) { // Use the callback form as anonymous types may be nested, and we want to // properly replace them even in that case. editor.ReplaceNode( childCreation, (currentNode, g) => { var currentAnonymousObject = (TAnonymousObjectCreationExpressionSyntax)currentNode; // If we hit the node the user started on, then add the rename annotation here. var className = classSymbol.Name; var classNameToken = startingCreationNode == childCreation ? g.Identifier(className).WithAdditionalAnnotations(RenameAnnotation.Create()) : g.Identifier(className); var classNameNode = classSymbol.TypeParameters.Length == 0 ? (TNameSyntax)g.IdentifierName(classNameToken) : (TNameSyntax)g.GenericName(classNameToken, classSymbol.TypeParameters.Select(tp => g.IdentifierName(tp.Name))); return CreateObjectCreationExpression(classNameNode, currentAnonymousObject) .WithAdditionalAnnotations(Formatter.Annotation); }); } private static async Task<INamedTypeSymbol> GenerateFinalNamedTypeAsync( Document document, string typeName, bool isRecord, ImmutableArray<IPropertySymbol> properties, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Next, see if any of the properties ended up using any type parameters from the // containing method/named-type. If so, we'll need to generate a generic type so we can // properly pass these along. var capturedTypeParameters = properties.Select(p => p.Type) .SelectMany(t => t.GetReferencedTypeParameters()) .Distinct() .ToImmutableArray(); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var members); if (isRecord) { // Create a record with a single primary constructor, containing a parameter for all the properties // we're generating. var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, Accessibility.Public, modifiers: default, typeName, properties.SelectAsArray(prop => CodeGenerationSymbolFactory.CreateParameterSymbol(prop.Type, prop.Name)), isPrimaryConstructor: true); members.Add(constructor); } else { // Now try to generate all the members that will go in the new class. This is a bit // circular. In order to generate some of the members, we need to know about the type. // But in order to create the type, we need the members. To address this we do two // passes. First, we create an empty version of the class. This can then be used to // help create members like Equals/GetHashCode. Then, once we have all the members we // create the final type. var namedTypeWithoutMembers = CreateNamedType(typeName, isRecord: false, capturedTypeParameters, members: default); var constructor = CreateClassConstructor(semanticModel, typeName, properties, generator); // Generate Equals/GetHashCode. Only readonly properties are suitable for these // methods. We can defer to our existing language service for this so that we // generate the same Equals/GetHashCode that our other IDE features generate. var readonlyProperties = ImmutableArray<ISymbol>.CastUp( properties.WhereAsArray(p => p.SetMethod == null)); var equalsAndGetHashCodeService = document.GetRequiredLanguageService<IGenerateEqualsAndGetHashCodeService>(); var equalsMethod = await equalsAndGetHashCodeService.GenerateEqualsMethodAsync( document, namedTypeWithoutMembers, readonlyProperties, localNameOpt: SyntaxGeneratorExtensions.OtherName, cancellationToken).ConfigureAwait(false); var getHashCodeMethod = await equalsAndGetHashCodeService.GenerateGetHashCodeMethodAsync( document, namedTypeWithoutMembers, readonlyProperties, cancellationToken).ConfigureAwait(false); members.AddRange(properties); members.Add(constructor); members.Add(equalsMethod); members.Add(getHashCodeMethod); } return CreateNamedType(typeName, isRecord, capturedTypeParameters, members.ToImmutable()); } private static INamedTypeSymbol CreateNamedType( string className, bool isRecord, ImmutableArray<ITypeParameterSymbol> capturedTypeParameters, ImmutableArray<ISymbol> members) { return CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, Accessibility.Internal, modifiers: default, isRecord, TypeKind.Class, className, capturedTypeParameters, members: members); } private static (ImmutableArray<IPropertySymbol> properties, ImmutableDictionary<IPropertySymbol, string> propertyMap) GenerateProperties( Document document, INamedTypeSymbol anonymousType) { var originalProperties = anonymousType.GetMembers().OfType<IPropertySymbol>().ToImmutableArray(); var newProperties = originalProperties.SelectAsArray(p => GenerateProperty(document, p)); // If we changed the names of any properties, record that name mapping. We'll // use this to update reference to the old anonymous-type properties to the new // names. var builder = ImmutableDictionary.CreateBuilder<IPropertySymbol, string>(); for (var i = 0; i < originalProperties.Length; i++) { var originalProperty = originalProperties[i]; var newProperty = newProperties[i]; if (originalProperty.Name != newProperty.Name) builder[originalProperty] = newProperty.Name; } return (newProperties, builder.ToImmutable()); } private static IPropertySymbol GenerateProperty(Document document, IPropertySymbol prop) { // The actual properties generated by C#/VB are not what we want. For example, they // think of themselves as having real accessors that will read/write into a real field // in the type. Instead, we just want to generate auto-props. So we effectively clone // the property, just throwing aways anything we don't need for that purpose. // // We also want to follow general .NET naming. So that means converting to pascal // case from camel-case. var getMethod = prop.GetMethod != null ? CreateAccessorSymbol(prop, MethodKind.PropertyGet) : null; var setMethod = prop.SetMethod != null ? CreateAccessorSymbol(prop, MethodKind.PropertySet) : null; return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default, Accessibility.Public, modifiers: default, prop.Type, refKind: default, explicitInterfaceImplementations: default, GetLegalName(prop.Name.ToPascalCase(trimLeadingTypePrefix: false), document), parameters: default, getMethod: getMethod, setMethod: setMethod); } private static string GetLegalName(string name, Document document) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); return syntaxFacts.IsLegalIdentifier(name) ? name : "Item"; // Just a dummy name for the property. Does not need to be localized. } private static IMethodSymbol CreateAccessorSymbol(IPropertySymbol prop, MethodKind kind) => CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, Accessibility.Public, DeclarationModifiers.Abstract, prop.Type, refKind: default, explicitInterfaceImplementations: default, name: "", typeParameters: default, parameters: default, methodKind: kind); private static IMethodSymbol CreateClassConstructor( SemanticModel semanticModel, string className, ImmutableArray<IPropertySymbol> properties, SyntaxGenerator generator) { // For every property, create a corresponding parameter, as well as an assignment // statement from that parameter to the property. var parameterToPropMap = new Dictionary<string, ISymbol>(); var parameters = properties.SelectAsArray(prop => { var parameter = CodeGenerationSymbolFactory.CreateParameterSymbol( prop.Type, prop.Name.ToCamelCase(trimLeadingTypePrefix: false)); parameterToPropMap[parameter.Name] = prop; return parameter; }); var assignmentStatements = generator.CreateAssignmentStatements( semanticModel, parameters, parameterToPropMap, ImmutableDictionary<string, string>.Empty, addNullChecks: false, preferThrowExpression: false); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, Accessibility.Public, modifiers: default, className, parameters, assignmentStatements); return constructor; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertAnonymousType { internal abstract class AbstractConvertAnonymousTypeToClassCodeRefactoringProvider< TExpressionSyntax, TNameSyntax, TIdentifierNameSyntax, TObjectCreationExpressionSyntax, TAnonymousObjectCreationExpressionSyntax, TNamespaceDeclarationSyntax> : AbstractConvertAnonymousTypeCodeRefactoringProvider<TAnonymousObjectCreationExpressionSyntax> where TExpressionSyntax : SyntaxNode where TNameSyntax : TExpressionSyntax where TIdentifierNameSyntax : TNameSyntax where TObjectCreationExpressionSyntax : TExpressionSyntax where TAnonymousObjectCreationExpressionSyntax : TExpressionSyntax where TNamespaceDeclarationSyntax : SyntaxNode { protected abstract TObjectCreationExpressionSyntax CreateObjectCreationExpression(TNameSyntax nameNode, TAnonymousObjectCreationExpressionSyntax currentAnonymousObject); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; var (anonymousObject, anonymousType) = await TryGetAnonymousObjectAsync(document, textSpan, cancellationToken).ConfigureAwait(false); if (anonymousObject == null || anonymousType == null) return; // Check if the anonymous type actually references another anonymous type inside of it. // If it does, we can't convert this. There is no way to describe this anonymous type // in the concrete type we create. var containsAnonymousType = anonymousType.GetMembers() .OfType<IPropertySymbol>() .Any(p => p.Type.ContainsAnonymousType()); if (containsAnonymousType) return; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (syntaxFacts.SupportsRecord(anonymousObject.SyntaxTree.Options)) { context.RegisterRefactoring(new MyCodeAction( FeaturesResources.Convert_to_record, c => ConvertAsync(document, textSpan, isRecord: true, c)), anonymousObject.Span); } context.RegisterRefactoring(new MyCodeAction( FeaturesResources.Convert_to_class, c => ConvertAsync(document, textSpan, isRecord: false, c)), anonymousObject.Span); } private async Task<Document> ConvertAsync(Document document, TextSpan span, bool isRecord, CancellationToken cancellationToken) { var (anonymousObject, anonymousType) = await TryGetAnonymousObjectAsync(document, span, cancellationToken).ConfigureAwait(false); Debug.Assert(anonymousObject != null); Debug.Assert(anonymousType != null); var position = span.Start; var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Generate a unique name for the class we're creating. We'll also add a rename // annotation so the user can pick the right name for the type afterwards. var className = NameGenerator.GenerateUniqueName( isRecord ? "NewRecord" : "NewClass", n => semanticModel.LookupSymbols(position, name: n).IsEmpty); // First, create the set of properties this class will have based on the properties the // anonymous type has itself. Also, get a mapping of the original anonymous type's // properties to the new name we generated for it (if we converted camelCase to // PascalCase). var (properties, propertyMap) = GenerateProperties(document, anonymousType); // Next, generate the full class that will be used to replace all instances of this // anonymous type. var namedTypeSymbol = await GenerateFinalNamedTypeAsync( document, className, isRecord, properties, cancellationToken).ConfigureAwait(false); var generator = SyntaxGenerator.GetGenerator(document); var editor = new SyntaxEditor(root, generator); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var containingMember = anonymousObject.FirstAncestorOrSelf<SyntaxNode, ISyntaxFactsService>((node, syntaxFacts) => syntaxFacts.IsMethodLevelMember(node), syntaxFacts) ?? anonymousObject; // Next, go and update any references to these anonymous type properties to match // the new PascalCased name we've picked for the new properties that will go in // the named type. await ReplacePropertyReferencesAsync( document, editor, containingMember, propertyMap, cancellationToken).ConfigureAwait(false); // Next, go through and replace all matching anonymous types in this method with a call // to construct the new named type we've generated. await ReplaceMatchingAnonymousTypesAsync( document, editor, namedTypeSymbol, containingMember, anonymousObject, anonymousType, cancellationToken).ConfigureAwait(false); // Then, actually insert the new class in the appropriate container. var container = anonymousObject.GetAncestor<TNamespaceDeclarationSyntax>() ?? root; editor.ReplaceNode(container, (currentContainer, _) => { var codeGenService = document.GetRequiredLanguageService<ICodeGenerationService>(); var codeGenOptions = new CodeGenerationOptions( generateMembers: true, sortMembers: false, autoInsertionLocation: false, options: options, parseOptions: root.SyntaxTree.Options); return codeGenService.AddNamedType( currentContainer, namedTypeSymbol, codeGenOptions, cancellationToken); }); var updatedDocument = document.WithSyntaxRoot(editor.GetChangedRoot()); // Finally, format using the equals+getHashCode service so that our generated methods // follow any special formatting rules specific to them. var equalsAndGetHashCodeService = document.GetRequiredLanguageService<IGenerateEqualsAndGetHashCodeService>(); return await equalsAndGetHashCodeService.FormatDocumentAsync( updatedDocument, cancellationToken).ConfigureAwait(false); } private static async Task ReplacePropertyReferencesAsync( Document document, SyntaxEditor editor, SyntaxNode containingMember, ImmutableDictionary<IPropertySymbol, string> propertyMap, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var identifiers = containingMember.DescendantNodes().OfType<TIdentifierNameSyntax>(); foreach (var identifier in identifiers) { if (!syntaxFacts.IsNameOfSimpleMemberAccessExpression(identifier) && !syntaxFacts.IsNameOfMemberBindingExpression(identifier)) { continue; } if (semanticModel.GetSymbolInfo(identifier, cancellationToken).GetAnySymbol() is not IPropertySymbol symbol) continue; if (propertyMap.TryGetValue(symbol, out var newName)) { editor.ReplaceNode( identifier, (currentId, g) => g.IdentifierName(newName).WithTriviaFrom(currentId)); } } } private async Task ReplaceMatchingAnonymousTypesAsync( Document document, SyntaxEditor editor, INamedTypeSymbol classSymbol, SyntaxNode containingMember, TAnonymousObjectCreationExpressionSyntax creationNode, INamedTypeSymbol anonymousType, CancellationToken cancellationToken) { // When invoked we want to fixup all creations of the "same" anonymous type within the // containing method. We define same-ness as meaning "they have the type symbol". this // means both have the same member names, in the same order, with the same member types. // We fix all these up in the method because the user may be creating several instances // of this anonymous type in that method and then combining them in interesting ways // (i.e. checking them for equality, using them in collections, etc.). The language // guarantees within a method boundary that these will be the same type and can be used // together in this fashion. // // Note: we could consider expanding this in the future (potentially with another // lightbulb action). Specifically, we could look in the containing type and replace // any matches in any methods. var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var childCreationNodes = containingMember.DescendantNodesAndSelf() .OfType<TAnonymousObjectCreationExpressionSyntax>(); foreach (var childCreation in childCreationNodes) { var childType = semanticModel.GetTypeInfo(childCreation, cancellationToken).Type; if (childType == null) { Debug.Fail("We should always be able to get an anonymous type for any anonymous creation node."); continue; } if (anonymousType.Equals(childType)) ReplaceWithObjectCreation(editor, classSymbol, creationNode, childCreation); } } private void ReplaceWithObjectCreation( SyntaxEditor editor, INamedTypeSymbol classSymbol, TAnonymousObjectCreationExpressionSyntax startingCreationNode, TAnonymousObjectCreationExpressionSyntax childCreation) { // Use the callback form as anonymous types may be nested, and we want to // properly replace them even in that case. editor.ReplaceNode( childCreation, (currentNode, g) => { var currentAnonymousObject = (TAnonymousObjectCreationExpressionSyntax)currentNode; // If we hit the node the user started on, then add the rename annotation here. var className = classSymbol.Name; var classNameToken = startingCreationNode == childCreation ? g.Identifier(className).WithAdditionalAnnotations(RenameAnnotation.Create()) : g.Identifier(className); var classNameNode = classSymbol.TypeParameters.Length == 0 ? (TNameSyntax)g.IdentifierName(classNameToken) : (TNameSyntax)g.GenericName(classNameToken, classSymbol.TypeParameters.Select(tp => g.IdentifierName(tp.Name))); return CreateObjectCreationExpression(classNameNode, currentAnonymousObject) .WithAdditionalAnnotations(Formatter.Annotation); }); } private static async Task<INamedTypeSymbol> GenerateFinalNamedTypeAsync( Document document, string typeName, bool isRecord, ImmutableArray<IPropertySymbol> properties, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Next, see if any of the properties ended up using any type parameters from the // containing method/named-type. If so, we'll need to generate a generic type so we can // properly pass these along. var capturedTypeParameters = properties.Select(p => p.Type) .SelectMany(t => t.GetReferencedTypeParameters()) .Distinct() .ToImmutableArray(); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var members); if (isRecord) { // Create a record with a single primary constructor, containing a parameter for all the properties // we're generating. var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, Accessibility.Public, modifiers: default, typeName, properties.SelectAsArray(prop => CodeGenerationSymbolFactory.CreateParameterSymbol(prop.Type, prop.Name)), isPrimaryConstructor: true); members.Add(constructor); } else { // Now try to generate all the members that will go in the new class. This is a bit // circular. In order to generate some of the members, we need to know about the type. // But in order to create the type, we need the members. To address this we do two // passes. First, we create an empty version of the class. This can then be used to // help create members like Equals/GetHashCode. Then, once we have all the members we // create the final type. var namedTypeWithoutMembers = CreateNamedType(typeName, isRecord: false, capturedTypeParameters, members: default); var constructor = CreateClassConstructor(semanticModel, typeName, properties, generator); // Generate Equals/GetHashCode. Only readonly properties are suitable for these // methods. We can defer to our existing language service for this so that we // generate the same Equals/GetHashCode that our other IDE features generate. var readonlyProperties = ImmutableArray<ISymbol>.CastUp( properties.WhereAsArray(p => p.SetMethod == null)); var equalsAndGetHashCodeService = document.GetRequiredLanguageService<IGenerateEqualsAndGetHashCodeService>(); var equalsMethod = await equalsAndGetHashCodeService.GenerateEqualsMethodAsync( document, namedTypeWithoutMembers, readonlyProperties, localNameOpt: SyntaxGeneratorExtensions.OtherName, cancellationToken).ConfigureAwait(false); var getHashCodeMethod = await equalsAndGetHashCodeService.GenerateGetHashCodeMethodAsync( document, namedTypeWithoutMembers, readonlyProperties, cancellationToken).ConfigureAwait(false); members.AddRange(properties); members.Add(constructor); members.Add(equalsMethod); members.Add(getHashCodeMethod); } return CreateNamedType(typeName, isRecord, capturedTypeParameters, members.ToImmutable()); } private static INamedTypeSymbol CreateNamedType( string className, bool isRecord, ImmutableArray<ITypeParameterSymbol> capturedTypeParameters, ImmutableArray<ISymbol> members) { return CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, Accessibility.Internal, modifiers: default, isRecord, TypeKind.Class, className, capturedTypeParameters, members: members); } private static (ImmutableArray<IPropertySymbol> properties, ImmutableDictionary<IPropertySymbol, string> propertyMap) GenerateProperties( Document document, INamedTypeSymbol anonymousType) { var originalProperties = anonymousType.GetMembers().OfType<IPropertySymbol>().ToImmutableArray(); var newProperties = originalProperties.SelectAsArray(p => GenerateProperty(document, p)); // If we changed the names of any properties, record that name mapping. We'll // use this to update reference to the old anonymous-type properties to the new // names. var builder = ImmutableDictionary.CreateBuilder<IPropertySymbol, string>(); for (var i = 0; i < originalProperties.Length; i++) { var originalProperty = originalProperties[i]; var newProperty = newProperties[i]; if (originalProperty.Name != newProperty.Name) builder[originalProperty] = newProperty.Name; } return (newProperties, builder.ToImmutable()); } private static IPropertySymbol GenerateProperty(Document document, IPropertySymbol prop) { // The actual properties generated by C#/VB are not what we want. For example, they // think of themselves as having real accessors that will read/write into a real field // in the type. Instead, we just want to generate auto-props. So we effectively clone // the property, just throwing aways anything we don't need for that purpose. // // We also want to follow general .NET naming. So that means converting to pascal // case from camel-case. var getMethod = prop.GetMethod != null ? CreateAccessorSymbol(prop, MethodKind.PropertyGet) : null; var setMethod = prop.SetMethod != null ? CreateAccessorSymbol(prop, MethodKind.PropertySet) : null; return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default, Accessibility.Public, modifiers: default, prop.Type, refKind: default, explicitInterfaceImplementations: default, GetLegalName(prop.Name.ToPascalCase(trimLeadingTypePrefix: false), document), parameters: default, getMethod: getMethod, setMethod: setMethod); } private static string GetLegalName(string name, Document document) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); return syntaxFacts.IsLegalIdentifier(name) ? name : "Item"; // Just a dummy name for the property. Does not need to be localized. } private static IMethodSymbol CreateAccessorSymbol(IPropertySymbol prop, MethodKind kind) => CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, Accessibility.Public, DeclarationModifiers.Abstract, prop.Type, refKind: default, explicitInterfaceImplementations: default, name: "", typeParameters: default, parameters: default, methodKind: kind); private static IMethodSymbol CreateClassConstructor( SemanticModel semanticModel, string className, ImmutableArray<IPropertySymbol> properties, SyntaxGenerator generator) { // For every property, create a corresponding parameter, as well as an assignment // statement from that parameter to the property. var parameterToPropMap = new Dictionary<string, ISymbol>(); var parameters = properties.SelectAsArray(prop => { var parameter = CodeGenerationSymbolFactory.CreateParameterSymbol( prop.Type, prop.Name.ToCamelCase(trimLeadingTypePrefix: false)); parameterToPropMap[parameter.Name] = prop; return parameter; }); var assignmentStatements = generator.CreateAssignmentStatements( semanticModel, parameters, parameterToPropMap, ImmutableDictionary<string, string>.Empty, addNullChecks: false, preferThrowExpression: false); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, Accessibility.Public, modifiers: default, className, parameters, assignmentStatements); return constructor; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/VisualStudio/Core/Def/Implementation/Preview/ReferenceChange.AnalyzerReferenceChange.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.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal abstract partial class ReferenceChange : AbstractChange { private sealed class AnalyzerReferenceChange : ReferenceChange { private readonly AnalyzerReference _reference; public AnalyzerReferenceChange(AnalyzerReference reference, ProjectId projectId, string projectName, bool isAdded, PreviewEngine engine) : base(projectId, projectName, isAdded, engine) { _reference = reference; } internal override Solution AddToSolution(Solution solution) => solution.AddAnalyzerReference(this.ProjectId, _reference); internal override Solution RemoveFromSolution(Solution solution) => solution.RemoveAnalyzerReference(this.ProjectId, _reference); protected override string GetDisplayText() { var display = _reference.Display ?? ServicesVSResources.Unknown1; return string.Format(ServicesVSResources.Analyzer_reference_to_0_in_project_1, display, this.ProjectName); } } } }
// 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.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal abstract partial class ReferenceChange : AbstractChange { private sealed class AnalyzerReferenceChange : ReferenceChange { private readonly AnalyzerReference _reference; public AnalyzerReferenceChange(AnalyzerReference reference, ProjectId projectId, string projectName, bool isAdded, PreviewEngine engine) : base(projectId, projectName, isAdded, engine) { _reference = reference; } internal override Solution AddToSolution(Solution solution) => solution.AddAnalyzerReference(this.ProjectId, _reference); internal override Solution RemoveFromSolution(Solution solution) => solution.RemoveAnalyzerReference(this.ProjectId, _reference); protected override string GetDisplayText() { var display = _reference.Display ?? ServicesVSResources.Unknown1; return string.Format(ServicesVSResources.Analyzer_reference_to_0_in_project_1, display, this.ProjectName); } } } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/Core/Portable/CodeCleanup/Providers/ICodeCleanupProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeCleanup.Providers { /// <summary> /// A code cleaner that requires semantic information to do its job. /// </summary> internal interface ICodeCleanupProvider { /// <summary> /// Returns the name of this provider. /// </summary> string Name { get; } /// <summary> /// This should apply its code clean up logic to the spans of the document. /// </summary> Task<Document> CleanupAsync(Document document, ImmutableArray<TextSpan> spans, CancellationToken cancellationToken = default); /// <summary> /// This will run all provided code cleaners in an order that is given to the method. /// /// This will do cleanups that don't require any semantic information /// </summary> Task<SyntaxNode> CleanupAsync(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken = default); } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeCleanup.Providers { /// <summary> /// A code cleaner that requires semantic information to do its job. /// </summary> internal interface ICodeCleanupProvider { /// <summary> /// Returns the name of this provider. /// </summary> string Name { get; } /// <summary> /// This should apply its code clean up logic to the spans of the document. /// </summary> Task<Document> CleanupAsync(Document document, ImmutableArray<TextSpan> spans, CancellationToken cancellationToken = default); /// <summary> /// This will run all provided code cleaners in an order that is given to the method. /// /// This will do cleanups that don't require any semantic information /// </summary> Task<SyntaxNode> CleanupAsync(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken = default); } }
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Test/Resources/Core/SymbolsTests/netModule/CrossRefModule2.netmodule
MZ@ !L!This program cannot be run in DOS mode. $PEL7P  " @@ `@!O@  H.text$  `.reloc @@B"HX t( *BSJB v4.0.30319l#~T#StringsL#UST#GUIDd#BlobG%390P 3  3  <Module>mscorlibM2CrossRefModule1.netmoduleM1.ctorCrossRefModule2.netmodule  G@LQ>)z\V4 !" "_CorExeMainmscoree.dll% @ 2
MZ@ !L!This program cannot be run in DOS mode. $PEL7P  " @@ `@!O@  H.text$  `.reloc @@B"HX t( *BSJB v4.0.30319l#~T#StringsL#UST#GUIDd#BlobG%390P 3  3  <Module>mscorlibM2CrossRefModule1.netmoduleM1.ctorCrossRefModule2.netmodule  G@LQ>)z\V4 !" "_CorExeMainmscoree.dll% @ 2
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Desktop.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 #if !NETCOREAPP using System; using System.Reflection; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Loads analyzer assemblies from their original locations in the file system. /// Assemblies will only be loaded from the locations specified when the loader /// is instantiated. /// </summary> /// <remarks> /// This type is meant to be used in scenarios where it is OK for the analyzer /// assemblies to be locked on disk for the lifetime of the host; for example, /// csc.exe and vbc.exe. In scenarios where support for updating or deleting /// the analyzer on disk is required a different loader should be used. /// </remarks> internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { private int _hookedAssemblyResolve; protected override Assembly LoadFromPathImpl(string fullPath) { if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0) { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } var pathToLoad = GetPathToLoad(fullPath); return Assembly.LoadFrom(pathToLoad); } private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { try { return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } catch { return null; } } } } #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 #if !NETCOREAPP using System; using System.Reflection; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Loads analyzer assemblies from their original locations in the file system. /// Assemblies will only be loaded from the locations specified when the loader /// is instantiated. /// </summary> /// <remarks> /// This type is meant to be used in scenarios where it is OK for the analyzer /// assemblies to be locked on disk for the lifetime of the host; for example, /// csc.exe and vbc.exe. In scenarios where support for updating or deleting /// the analyzer on disk is required a different loader should be used. /// </remarks> internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { private int _hookedAssemblyResolve; protected override Assembly LoadFromPathImpl(string fullPath) { if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0) { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } var pathToLoad = GetPathToLoad(fullPath); return Assembly.LoadFrom(pathToLoad); } private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { try { return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } catch { return null; } } } } #endif
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/VisualBasic/Test/Semantic/Semantics/PrintResultTestSource.vb
' 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. Imports System Imports System.Globalization Module PrintHelper Function GetCultureInvariantString(val As Object) As String If val Is Nothing Then Return Nothing End If Dim vType = val.GetType() Dim valStr = val.ToString() If vType Is GetType(DateTime) Then valStr = DirectCast(val, DateTime).ToString("M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture) ElseIf vType Is GetType(Single) Then valStr = DirectCast(val, Single).ToString(CultureInfo.InvariantCulture) ElseIf vType Is GetType(Double) Then valStr = DirectCast(val, Double).ToString(CultureInfo.InvariantCulture) ElseIf vType Is GetType(Decimal) Then valStr = DirectCast(val, Decimal).ToString(CultureInfo.InvariantCulture) End If Return valStr End Function Sub PrintResult(val As Boolean) Console.WriteLine("Boolean: {0}", val) End Sub Sub PrintResult(val As SByte) Console.WriteLine("SByte: {0}", val) End Sub Sub PrintResult(val As Byte) Console.WriteLine("Byte: {0}", val) End Sub Sub PrintResult(val As Short) Console.WriteLine("Short: {0}", val) End Sub Sub PrintResult(val As UShort) Console.WriteLine("UShort: {0}", val) End Sub Sub PrintResult(val As Integer) Console.WriteLine("Integer: {0}", val) End Sub Sub PrintResult(val As UInteger) Console.WriteLine("UInteger: {0}", val) End Sub Sub PrintResult(val As Long) Console.WriteLine("Long: {0}", val) End Sub Sub PrintResult(val As ULong) Console.WriteLine("ULong: {0}", val) End Sub Sub PrintResult(val As Decimal) Console.WriteLine("Decimal: {0}", GetCultureInvariantString(val)) End Sub Sub PrintResult(val As Single) Console.WriteLine("Single: {0}", GetCultureInvariantString(val)) End Sub Sub PrintResult(val As Double) Console.WriteLine("Double: {0}", GetCultureInvariantString(val)) End Sub Sub PrintResult(val As Date) Console.WriteLine("Date: {0}", GetCultureInvariantString(val)) End Sub Sub PrintResult(val As Char) Console.WriteLine("Char: [{0}]", val) End Sub Sub PrintResult(val As Char()) Console.WriteLine("Char(): {0}", New String(val)) End Sub Sub PrintResult(val As String) Console.WriteLine("String: [{0}]", val) End Sub Sub PrintResult(val As Object) Console.WriteLine("Object: [{0}]", val) End Sub Sub PrintResult(val As Guid) Console.WriteLine("Guid: {0}", val) End Sub Sub PrintResult(val As ValueType) Dim pval = GetCultureInvariantString(val) Console.WriteLine("ValueType: [{0}]", pval) End Sub Sub PrintResult(val As IComparable) Console.WriteLine("IComparable: [{0}]", val) End Sub ' ================================================================= Sub PrintResult(expr As String, val As Boolean) System.Console.WriteLine("[{1}] Boolean: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As SByte) System.Console.WriteLine("[{1}] SByte: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As Byte) System.Console.WriteLine("[{1}] Byte: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As Short) System.Console.WriteLine("[{1}] Short: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As UShort) System.Console.WriteLine("[{1}] UShort: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As Integer) System.Console.WriteLine("[{1}] Integer: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As UInteger) System.Console.WriteLine("[{1}] UInteger: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As Long) System.Console.WriteLine("[{1}] Long: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As ULong) System.Console.WriteLine("[{1}] ULong: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As Decimal) System.Console.WriteLine("[{1}] Decimal: {0}", GetCultureInvariantString(val), expr) End Sub Sub PrintResult(expr As String, val As Single) System.Console.WriteLine("[{1}] Single: {0}", GetCultureInvariantString(val), expr) End Sub Sub PrintResult(expr As String, val As Double) System.Console.WriteLine("[{1}] Double: {0}", GetCultureInvariantString(val), expr) End Sub Sub PrintResult(expr As String, val As Date) System.Console.WriteLine("[{1}] Date: {0}", GetCultureInvariantString(val), expr) End Sub Sub PrintResult(expr As String, val As Char) System.Console.WriteLine("[{1}] Char: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As String) System.Console.WriteLine("[{0}] String: [{1}]", expr, val) End Sub Sub PrintResult(expr As String, val As Object) System.Console.WriteLine("[{1}] Object: {0}", GetCultureInvariantString(val), expr) End Sub Sub PrintResult(expr As String, val As System.TypeCode) System.Console.WriteLine("[{1}] TypeCode: {0}", val, expr) End Sub End Module
' 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. Imports System Imports System.Globalization Module PrintHelper Function GetCultureInvariantString(val As Object) As String If val Is Nothing Then Return Nothing End If Dim vType = val.GetType() Dim valStr = val.ToString() If vType Is GetType(DateTime) Then valStr = DirectCast(val, DateTime).ToString("M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture) ElseIf vType Is GetType(Single) Then valStr = DirectCast(val, Single).ToString(CultureInfo.InvariantCulture) ElseIf vType Is GetType(Double) Then valStr = DirectCast(val, Double).ToString(CultureInfo.InvariantCulture) ElseIf vType Is GetType(Decimal) Then valStr = DirectCast(val, Decimal).ToString(CultureInfo.InvariantCulture) End If Return valStr End Function Sub PrintResult(val As Boolean) Console.WriteLine("Boolean: {0}", val) End Sub Sub PrintResult(val As SByte) Console.WriteLine("SByte: {0}", val) End Sub Sub PrintResult(val As Byte) Console.WriteLine("Byte: {0}", val) End Sub Sub PrintResult(val As Short) Console.WriteLine("Short: {0}", val) End Sub Sub PrintResult(val As UShort) Console.WriteLine("UShort: {0}", val) End Sub Sub PrintResult(val As Integer) Console.WriteLine("Integer: {0}", val) End Sub Sub PrintResult(val As UInteger) Console.WriteLine("UInteger: {0}", val) End Sub Sub PrintResult(val As Long) Console.WriteLine("Long: {0}", val) End Sub Sub PrintResult(val As ULong) Console.WriteLine("ULong: {0}", val) End Sub Sub PrintResult(val As Decimal) Console.WriteLine("Decimal: {0}", GetCultureInvariantString(val)) End Sub Sub PrintResult(val As Single) Console.WriteLine("Single: {0}", GetCultureInvariantString(val)) End Sub Sub PrintResult(val As Double) Console.WriteLine("Double: {0}", GetCultureInvariantString(val)) End Sub Sub PrintResult(val As Date) Console.WriteLine("Date: {0}", GetCultureInvariantString(val)) End Sub Sub PrintResult(val As Char) Console.WriteLine("Char: [{0}]", val) End Sub Sub PrintResult(val As Char()) Console.WriteLine("Char(): {0}", New String(val)) End Sub Sub PrintResult(val As String) Console.WriteLine("String: [{0}]", val) End Sub Sub PrintResult(val As Object) Console.WriteLine("Object: [{0}]", val) End Sub Sub PrintResult(val As Guid) Console.WriteLine("Guid: {0}", val) End Sub Sub PrintResult(val As ValueType) Dim pval = GetCultureInvariantString(val) Console.WriteLine("ValueType: [{0}]", pval) End Sub Sub PrintResult(val As IComparable) Console.WriteLine("IComparable: [{0}]", val) End Sub ' ================================================================= Sub PrintResult(expr As String, val As Boolean) System.Console.WriteLine("[{1}] Boolean: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As SByte) System.Console.WriteLine("[{1}] SByte: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As Byte) System.Console.WriteLine("[{1}] Byte: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As Short) System.Console.WriteLine("[{1}] Short: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As UShort) System.Console.WriteLine("[{1}] UShort: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As Integer) System.Console.WriteLine("[{1}] Integer: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As UInteger) System.Console.WriteLine("[{1}] UInteger: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As Long) System.Console.WriteLine("[{1}] Long: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As ULong) System.Console.WriteLine("[{1}] ULong: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As Decimal) System.Console.WriteLine("[{1}] Decimal: {0}", GetCultureInvariantString(val), expr) End Sub Sub PrintResult(expr As String, val As Single) System.Console.WriteLine("[{1}] Single: {0}", GetCultureInvariantString(val), expr) End Sub Sub PrintResult(expr As String, val As Double) System.Console.WriteLine("[{1}] Double: {0}", GetCultureInvariantString(val), expr) End Sub Sub PrintResult(expr As String, val As Date) System.Console.WriteLine("[{1}] Date: {0}", GetCultureInvariantString(val), expr) End Sub Sub PrintResult(expr As String, val As Char) System.Console.WriteLine("[{1}] Char: {0}", val, expr) End Sub Sub PrintResult(expr As String, val As String) System.Console.WriteLine("[{0}] String: [{1}]", expr, val) End Sub Sub PrintResult(expr As String, val As Object) System.Console.WriteLine("[{1}] Object: {0}", GetCultureInvariantString(val), expr) End Sub Sub PrintResult(expr As String, val As System.TypeCode) System.Console.WriteLine("[{1}] TypeCode: {0}", val, expr) End Sub End Module
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/VisualBasicProject.vbproj
<?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 ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion></ProductVersion> <SchemaVersion></SchemaVersion> <ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>VisualBasicProject</RootNamespace> <AssemblyName>VisualBasicProject</AssemblyName> <FileAlignment>512</FileAlignment> <MyType>Windows</MyType> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>bin\Debug\</OutputPath> <DocumentationFile>VisualBasicProject.xml</DocumentationFile> <NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> <RemoveIntegerChecks>true</RemoveIntegerChecks> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> <DefineConstants>FURBY</DefineConstants> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DefineDebug>false</DefineDebug> <DefineTrace>true</DefineTrace> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DocumentationFile>VisualBasicProject.xml</DocumentationFile> <NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> </PropertyGroup> <PropertyGroup> <OptionExplicit>On</OptionExplicit> <LangVersion>15</LangVersion> </PropertyGroup> <PropertyGroup> <OptionCompare>Binary</OptionCompare> </PropertyGroup> <PropertyGroup> <OptionStrict>Off</OptionStrict> </PropertyGroup> <PropertyGroup> <OptionInfer>On</OptionInfer> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Import Include="Microsoft.VisualBasic" /> <Import Include="System" /> <Import Include="System.Collections" /> <Import Include="System.Collections.Generic" /> <Import Include="System.Diagnostics" /> <Import Include="System.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="My Project\Application.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Application.myapp</DependentUpon> </Compile> <Compile Include="My Project\AssemblyInfo.vb" /> <Compile Include="My Project\Resources.Designer.vb"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon> </Compile> <Compile Include="My Project\Settings.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> <Compile Include="VisualBasicClass.vb" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="My Project\Resources.resx"> <Generator>VbMyResourcesResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.vb</LastGenOutput> <CustomToolNamespace>My.Resources</CustomToolNamespace> <SubType>Designer</SubType> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="My Project\Application.myapp"> <Generator>MyApplicationCodeGenerator</Generator> <LastGenOutput>Application.Designer.vb</LastGenOutput> </None> <None Include="My Project\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <CustomToolNamespace>My</CustomToolNamespace> <LastGenOutput>Settings.Designer.vb</LastGenOutput> </None> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CSharpProject\CSharpProject.csproj"> <Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project> <Name>CSharpProject</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </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 ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion></ProductVersion> <SchemaVersion></SchemaVersion> <ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>VisualBasicProject</RootNamespace> <AssemblyName>VisualBasicProject</AssemblyName> <FileAlignment>512</FileAlignment> <MyType>Windows</MyType> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>bin\Debug\</OutputPath> <DocumentationFile>VisualBasicProject.xml</DocumentationFile> <NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> <RemoveIntegerChecks>true</RemoveIntegerChecks> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> <DefineConstants>FURBY</DefineConstants> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <DefineDebug>false</DefineDebug> <DefineTrace>true</DefineTrace> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DocumentationFile>VisualBasicProject.xml</DocumentationFile> <NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> </PropertyGroup> <PropertyGroup> <OptionExplicit>On</OptionExplicit> <LangVersion>15</LangVersion> </PropertyGroup> <PropertyGroup> <OptionCompare>Binary</OptionCompare> </PropertyGroup> <PropertyGroup> <OptionStrict>Off</OptionStrict> </PropertyGroup> <PropertyGroup> <OptionInfer>On</OptionInfer> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Import Include="Microsoft.VisualBasic" /> <Import Include="System" /> <Import Include="System.Collections" /> <Import Include="System.Collections.Generic" /> <Import Include="System.Diagnostics" /> <Import Include="System.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="My Project\Application.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Application.myapp</DependentUpon> </Compile> <Compile Include="My Project\AssemblyInfo.vb" /> <Compile Include="My Project\Resources.Designer.vb"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon> </Compile> <Compile Include="My Project\Settings.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> <Compile Include="VisualBasicClass.vb" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="My Project\Resources.resx"> <Generator>VbMyResourcesResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.vb</LastGenOutput> <CustomToolNamespace>My.Resources</CustomToolNamespace> <SubType>Designer</SubType> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="My Project\Application.myapp"> <Generator>MyApplicationCodeGenerator</Generator> <LastGenOutput>Application.Designer.vb</LastGenOutput> </None> <None Include="My Project\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <CustomToolNamespace>My</CustomToolNamespace> <LastGenOutput>Settings.Designer.vb</LastGenOutput> </None> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CSharpProject\CSharpProject.csproj"> <Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project> <Name>CSharpProject</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
56,433
Only allow Contract.ThrowIfNull() to be called on nullable types
We had some places we were calling it on bools.
jasonmalinowski
"2021-09-16T01:20:43Z"
"2021-09-16T18:44:11Z"
736fc1b5e6e2847689c0154b3e5f23ea99dd56af
6d0f4e3f972ceb561b04574e7f957a4ff458e272
Only allow Contract.ThrowIfNull() to be called on nullable types. We had some places we were calling it on bools.
./src/Compilers/Core/Portable/InternalUtilities/RoslynParallel.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; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal static class RoslynParallel { internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions(); /// <inheritdoc cref="Parallel.For(int, int, ParallelOptions, Action{int})"/> public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body, CancellationToken cancellationToken) { var parallelOptions = cancellationToken.CanBeCanceled ? new ParallelOptions { CancellationToken = cancellationToken } : DefaultParallelOptions; return Parallel.For(fromInclusive, toExclusive, parallelOptions, errorHandlingBody); // Local function void errorHandlingBody(int i) { try { body(i); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested && e.CancellationToken != cancellationToken) { // Parallel.For checks for a specific cancellation token, so make sure we throw with the // correct one. cancellationToken.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; } } } } }
// 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; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal static class RoslynParallel { internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions(); /// <inheritdoc cref="Parallel.For(int, int, ParallelOptions, Action{int})"/> public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body, CancellationToken cancellationToken) { var parallelOptions = cancellationToken.CanBeCanceled ? new ParallelOptions { CancellationToken = cancellationToken } : DefaultParallelOptions; return Parallel.For(fromInclusive, toExclusive, parallelOptions, errorHandlingBody); // Local function void errorHandlingBody(int i) { try { body(i); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } catch (OperationCanceledException e) when (cancellationToken.IsCancellationRequested && e.CancellationToken != cancellationToken) { // Parallel.For checks for a specific cancellation token, so make sure we throw with the // correct one. cancellationToken.ThrowIfCancellationRequested(); throw ExceptionUtilities.Unreachable; } } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/CodeAnalysisTest/DefaultAnalyzerAssemblyLoaderTests.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.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { [CollectionDefinition(Name)] public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture> { public const string Name = nameof(AssemblyLoadTestFixtureCollection); private AssemblyLoadTestFixtureCollection() { } } [Collection(AssemblyLoadTestFixtureCollection.Name)] public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); private readonly ITestOutputHelper _output; private readonly AssemblyLoadTestFixture _testFixture; public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture) { _output = output; _testFixture = testFixture; } [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var analyzerDependencyFile = _testFixture.AnalyzerDependency; var analyzerMainFile = _testFixture.AnalyzerWithDependency; var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(analyzerDependencyFile.Path); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); } [Fact] public void AddDependencyLocationThrowsOnNull() { var loader = new DefaultAnalyzerAssemblyLoader(); Assert.Throws<ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null)); Assert.Throws<ArgumentException>("fullPath", () => loader.AddDependencyLocation("a")); } [Fact] public void ThrowsForMissingFile() { var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll"); var loader = new DefaultAnalyzerAssemblyLoader(); Assert.ThrowsAny<Exception>(() => loader.LoadFromPath(path)); } [Fact] public void BasicLoad() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); Assert.NotNull(alpha); } [Fact] public void AssemblyLoading() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); var a = alpha.CreateInstance("Alpha.A")!; a.GetType().GetMethod("Write")!.Invoke(a, new object[] { sb, "Test A" }); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; b.GetType().GetMethod("Write")!.Invoke(b, new object[] { sb, "Test B" }); var expected = @"Delta: Gamma: Alpha: Test A Delta: Gamma: Beta: Test B "; var actual = sb.ToString(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_AssemblyLocationNotAdded() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assert.Throws<FileNotFoundException>(() => loader.LoadFromPath(_testFixture.Beta.Path)); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_DependencyLocationNotAdded() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect // calling Beta.B.Write to fail. loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; var writeMethod = b.GetType().GetMethod("Write")!; var exception = Assert.Throws<TargetInvocationException>( () => writeMethod.Invoke(b, new object[] { sb, "Test B" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); var actual = sb.ToString(); Assert.Equal(@"", actual); } private static void VerifyAssemblies(IEnumerable<Assembly> assemblies, params (string simpleName, string version, string path)[] expected) { Assert.Equal(expected, assemblies.Select(assembly => (assembly.GetName().Name!, assembly.GetName().Version!.ToString(), assembly.Location)).Order()); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_DependencyInDifferentDirectory() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); var tempDir = Temp.CreateDirectory(); var deltaFile = tempDir.CreateFile("Delta.dll").CopyContentFrom(_testFixture.Delta1.Path); loader.AddDependencyLocation(deltaFile.Path); loader.AddDependencyLocation(_testFixture.Gamma.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var b = gamma.CreateInstance("Gamma.G")!; var writeMethod = b.GetType().GetMethod("Write")!; writeMethod.Invoke(b, new object[] { sb, "Test G" }); var actual = sb.ToString(); Assert.Equal(@"Delta: Gamma: Test G ", actual); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(1, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "1.0.0.0", deltaFile.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) ); #endif } [Fact] public void AssemblyLoading_MultipleVersions() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(2, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) ); VerifyAssemblies( alcs[1].Assemblies, ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_NoExactMatch() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta3.Path); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(1, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "3.0.0.0", _testFixture.Delta3.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta.3: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MultipleEqualMatches() { StringBuilder sb = new StringBuilder(); // Delta2B and Delta2 have the same version, but we prefer Delta2 because it's in the same directory as Epsilon. var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Delta2B.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(1, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_ExactAndGreaterMatch() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Delta2B.Path); loader.AddDependencyLocation(_testFixture.Delta3.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(1, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "2.0.0.0", _testFixture.Delta2B.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta.2B: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_WorseMatchInSameDirectory() { StringBuilder sb = new StringBuilder(); var tempDir = Temp.CreateDirectory(); var epsilonFile = tempDir.CreateFile("Epsilon.dll").CopyContentFrom(_testFixture.Epsilon.Path); var delta1File = tempDir.CreateFile("Delta.dll").CopyContentFrom(_testFixture.Delta1.Path); // Epsilon wants Delta2, but since Delta1 is in the same directory, we prefer Delta1 over Delta2. var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(delta1File.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); loader.AddDependencyLocation(epsilonFile.Path); Assembly epsilon = loader.LoadFromPath(epsilonFile.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(1, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "1.0.0.0", delta1File.Path), ("Epsilon", "0.0.0.0", epsilonFile.Path)); #endif var actual = sb.ToString(); Assert.Equal( @"Delta: Epsilon: Test E ", actual); } [Fact] public void AssemblyLoading_MultipleVersions_MultipleLoaders() { StringBuilder sb = new StringBuilder(); var loader1 = new DefaultAnalyzerAssemblyLoader(); loader1.AddDependencyLocation(_testFixture.Gamma.Path); loader1.AddDependencyLocation(_testFixture.Delta1.Path); var loader2 = new DefaultAnalyzerAssemblyLoader(); loader2.AddDependencyLocation(_testFixture.Epsilon.Path); loader2.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1); Assert.Equal(1, alcs1.Length); VerifyAssemblies( alcs1[0].Assemblies, ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path)); var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2); Assert.Equal(1, alcs2.Length); VerifyAssemblies( alcs2[0].Assemblies, ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MissingVersion() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; var eWrite = e.GetType().GetMethod("Write")!; var actual = sb.ToString(); eWrite.Invoke(e, new object[] { sb, "Test E" }); Assert.Equal( @"Delta: Gamma: Test G ", actual); } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; if (ExecutionConditionUtil.IsCoreClr) { var ex = Assert.ThrowsAny<Exception>(() => analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb })); Assert.True(ex is MissingMethodException or TargetInvocationException, $@"Unexpected exception type: ""{ex.GetType()}"""); } else { analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal("42", sb.ToString()); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal(ExecutionConditionUtil.IsCoreClr ? "1" : "42", sb.ToString()); } [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))] public void AssemblyLoading_NativeDependency() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path); var analyzer = analyzerAssembly.CreateInstance("Class1")!; var result = analyzer.GetType().GetMethod("GetFileAttributes")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path }); Assert.Equal(0, Marshal.GetLastWin32Error()); Assert.Equal(FileAttributes.Archive, (FileAttributes)result!); } [Fact] public void AssemblyLoading_Delete() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); var tempDir = Temp.CreateDirectory(); var deltaCopy = tempDir.CreateFile("Delta.dll").CopyContentFrom(_testFixture.Delta1.Path); loader.AddDependencyLocation(deltaCopy.Path); Assembly delta = loader.LoadFromPath(deltaCopy.Path); try { File.Delete(deltaCopy.Path); } catch (UnauthorizedAccessException) { return; } // The above call may or may not throw depending on the platform configuration. // If it doesn't throw, we might as well check that things are still functioning reasonably. var d = delta.CreateInstance("Delta.D"); d!.GetType().GetMethod("Write")!.Invoke(d, new object[] { sb, "Test D" }); var actual = sb.ToString(); Assert.Equal( @"Delta: Test D ", actual); } #if NETCOREAPP [Fact] public void VerifyCompilerAssemblySimpleNames() { var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly; var caReferences = caAssembly.GetReferencedAssemblies(); var allReferenceSimpleNames = ArrayBuilder<string>.GetInstance(); allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in caReferences) { allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException()); } var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly; allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException()); var csReferences = csAssembly.GetReferencedAssemblies(); foreach (var reference in csReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly; var vbReferences = vbAssembly.GetReferencedAssemblies(); allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in vbReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames)) { allReferenceSimpleNames.Sort(); var allNames = string.Join(",\r\n ", allReferenceSimpleNames.Select(name => $@"""{name}""")); _output.WriteLine(" internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames ="); _output.WriteLine(" ImmutableHashSet.Create("); _output.WriteLine(" StringComparer.OrdinalIgnoreCase,"); _output.WriteLine($" {allNames});"); allReferenceSimpleNames.Free(); Assert.True(false, $"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it."); } else { allReferenceSimpleNames.Free(); } } [Fact] public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesSystemCollectionsImmutable() { // Create a separate ALC as the compiler context, load the compiler assembly and a modified version of S.C.I into it, // then use that to load and run `AssemblyLoadingInNonDefaultContextHelper1` below. We expect the analyzer running in // its own `DirectoryLoadContext` would use the bogus S.C.I loaded in the compiler load context instead of the real one // in the default context. var compilerContext = new System.Runtime.Loader.AssemblyLoadContext("compilerContext"); _ = compilerContext.LoadFromAssemblyPath(_testFixture.UserSystemCollectionsImmutable.Path); _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location); var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location); var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!, ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!; StringBuilder sb = new StringBuilder(); testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper1), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb }); Assert.Equal("42", sb.ToString()); } // This helper does the same thing as in `AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01` test above except the assertions. private void AssemblyLoadingInNonDefaultContextHelper1(StringBuilder sb) { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); } [Fact] public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesNonCompilerAssemblyUsedByDefaultContext() { // Load the V2 of Delta to default ALC, then create a separate ALC for compiler and load compiler assembly. // Next use compiler context to load and run `AssemblyLoadingInNonDefaultContextHelper2` below. We expect the analyzer running in // its own `DirectoryLoadContext` would load and use Delta V1 located in its directory instead of V2 already loaded in the default context. _ = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(_testFixture.Delta2.Path); var compilerContext = new System.Runtime.Loader.AssemblyLoadContext("compilerContext"); _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location); var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location); var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!, ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!; StringBuilder sb = new StringBuilder(); testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper2), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb }); Assert.Equal( @"Delta: Hello ", sb.ToString()); } private void AssemblyLoadingInNonDefaultContextHelper2(StringBuilder sb) { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesDelta1.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesDelta1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); } #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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { [CollectionDefinition(Name)] public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture> { public const string Name = nameof(AssemblyLoadTestFixtureCollection); private AssemblyLoadTestFixtureCollection() { } } [Collection(AssemblyLoadTestFixtureCollection.Name)] public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); private readonly ITestOutputHelper _output; private readonly AssemblyLoadTestFixture _testFixture; public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture) { _output = output; _testFixture = testFixture; } [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var analyzerDependencyFile = _testFixture.AnalyzerDependency; var analyzerMainFile = _testFixture.AnalyzerWithDependency; var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(analyzerDependencyFile.Path); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); } [Fact] public void AddDependencyLocationThrowsOnNull() { var loader = new DefaultAnalyzerAssemblyLoader(); Assert.Throws<ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null!)); Assert.Throws<ArgumentException>("fullPath", () => loader.AddDependencyLocation("a")); } [Fact] public void ThrowsForMissingFile() { var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll"); var loader = new DefaultAnalyzerAssemblyLoader(); Assert.ThrowsAny<Exception>(() => loader.LoadFromPath(path)); } [Fact] public void BasicLoad() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); Assert.NotNull(alpha); } [Fact] public void AssemblyLoading() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); var a = alpha.CreateInstance("Alpha.A")!; a.GetType().GetMethod("Write")!.Invoke(a, new object[] { sb, "Test A" }); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; b.GetType().GetMethod("Write")!.Invoke(b, new object[] { sb, "Test B" }); var expected = @"Delta: Gamma: Alpha: Test A Delta: Gamma: Beta: Test B "; var actual = sb.ToString(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_AssemblyLocationNotAdded() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assert.Throws<FileNotFoundException>(() => loader.LoadFromPath(_testFixture.Beta.Path)); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_DependencyLocationNotAdded() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect // calling Beta.B.Write to fail. loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; var writeMethod = b.GetType().GetMethod("Write")!; var exception = Assert.Throws<TargetInvocationException>( () => writeMethod.Invoke(b, new object[] { sb, "Test B" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); var actual = sb.ToString(); Assert.Equal(@"", actual); } private static void VerifyAssemblies(IEnumerable<Assembly> assemblies, params (string simpleName, string version, string path)[] expected) { Assert.Equal(expected, assemblies.Select(assembly => (assembly.GetName().Name!, assembly.GetName().Version!.ToString(), assembly.Location)).Order()); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_DependencyInDifferentDirectory() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); var tempDir = Temp.CreateDirectory(); var deltaFile = tempDir.CreateFile("Delta.dll").CopyContentFrom(_testFixture.Delta1.Path); loader.AddDependencyLocation(deltaFile.Path); loader.AddDependencyLocation(_testFixture.Gamma.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var b = gamma.CreateInstance("Gamma.G")!; var writeMethod = b.GetType().GetMethod("Write")!; writeMethod.Invoke(b, new object[] { sb, "Test G" }); var actual = sb.ToString(); Assert.Equal(@"Delta: Gamma: Test G ", actual); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(1, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "1.0.0.0", deltaFile.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) ); #endif } [Fact] public void AssemblyLoading_MultipleVersions() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(2, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) ); VerifyAssemblies( alcs[1].Assemblies, ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_NoExactMatch() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta3.Path); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(1, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "3.0.0.0", _testFixture.Delta3.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta.3: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MultipleEqualMatches() { StringBuilder sb = new StringBuilder(); // Delta2B and Delta2 have the same version, but we prefer Delta2 because it's in the same directory as Epsilon. var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Delta2B.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(1, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MultipleVersionsOfSameAnalyzerItself() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Delta2.Path); loader.AddDependencyLocation(_testFixture.Delta2B.Path); Assembly delta2 = loader.LoadFromPath(_testFixture.Delta2.Path); Assembly delta2B = loader.LoadFromPath(_testFixture.Delta2B.Path); // 2B or not 2B? That is the question...that depends on whether we're on .NET Core or not. #if NETCOREAPP // On Core, we're able to load both of these into separate AssemblyLoadContexts. Assert.NotEqual(delta2B.Location, delta2.Location); Assert.Equal(_testFixture.Delta2.Path, delta2.Location); Assert.Equal(_testFixture.Delta2B.Path, delta2B.Location); #else // In non-core, we cache by assembly identity; since we don't use multiple AppDomains we have no // way to load different assemblies with the same identity, no matter what. Thus, we'll get the // same assembly for both of these. Assert.Same(delta2B, delta2); #endif } [Fact] public void AssemblyLoading_MultipleVersions_ExactAndGreaterMatch() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Delta2B.Path); loader.AddDependencyLocation(_testFixture.Delta3.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(1, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "2.0.0.0", _testFixture.Delta2B.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta.2B: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_WorseMatchInSameDirectory() { StringBuilder sb = new StringBuilder(); var tempDir = Temp.CreateDirectory(); var epsilonFile = tempDir.CreateFile("Epsilon.dll").CopyContentFrom(_testFixture.Epsilon.Path); var delta1File = tempDir.CreateFile("Delta.dll").CopyContentFrom(_testFixture.Delta1.Path); // Epsilon wants Delta2, but since Delta1 is in the same directory, we prefer Delta1 over Delta2. // This is because the CLR will see it first and load it, without giving us any chance to redirect // in the AssemblyResolve hook. var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(delta1File.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); loader.AddDependencyLocation(epsilonFile.Path); Assembly epsilon = loader.LoadFromPath(epsilonFile.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(1, alcs.Length); VerifyAssemblies( alcs[0].Assemblies, ("Delta", "1.0.0.0", delta1File.Path), ("Epsilon", "0.0.0.0", epsilonFile.Path)); #endif var actual = sb.ToString(); Assert.Equal( @"Delta: Epsilon: Test E ", actual); } [Fact] public void AssemblyLoading_MultipleVersions_MultipleLoaders() { StringBuilder sb = new StringBuilder(); var loader1 = new DefaultAnalyzerAssemblyLoader(); loader1.AddDependencyLocation(_testFixture.Gamma.Path); loader1.AddDependencyLocation(_testFixture.Delta1.Path); var loader2 = new DefaultAnalyzerAssemblyLoader(); loader2.AddDependencyLocation(_testFixture.Epsilon.Path); loader2.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1); Assert.Equal(1, alcs1.Length); VerifyAssemblies( alcs1[0].Assemblies, ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path)); var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2); Assert.Equal(1, alcs2.Length); VerifyAssemblies( alcs2[0].Assemblies, ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path)); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MissingVersion() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; var eWrite = e.GetType().GetMethod("Write")!; var actual = sb.ToString(); eWrite.Invoke(e, new object[] { sb, "Test E" }); Assert.Equal( @"Delta: Gamma: Test G ", actual); } [Fact] public void AssemblyLoading_UnifyToHighest() { var sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); // Gamma depends on Delta v1, and Epsilon depends on Delta v2. But both should load // and both use Delta v2. We intentionally here are not adding a reference to Delta1, since // this test is testing what happens if it's not present. A simple example for this scenario // is an analyzer that depends on both Gamma and Epsilon; an analyzer package can't reasonably // package both Delta v1 and Delta v2, so it'll only package the highest and things should work. loader.AddDependencyLocation(_testFixture.GammaReferencingPublicSigned.Path); loader.AddDependencyLocation(_testFixture.EpsilonReferencingPublicSigned.Path); loader.AddDependencyLocation(_testFixture.DeltaPublicSigned2.Path); var gamma = loader.LoadFromPath(_testFixture.GammaReferencingPublicSigned.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); var epsilon = loader.LoadFromPath(_testFixture.EpsilonReferencingPublicSigned.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); var actual = sb.ToString(); Assert.Equal( @"Delta.2: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } [Fact] public void AssemblyLoading_CanLoadDifferentVersionsDirectly() { var sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); // Ensure that no matter what, if we have two analyzers of different versions, we never unify them. loader.AddDependencyLocation(_testFixture.DeltaPublicSigned1.Path); loader.AddDependencyLocation(_testFixture.DeltaPublicSigned2.Path); var delta1Assembly = loader.LoadFromPath(_testFixture.DeltaPublicSigned1.Path); var delta1Instance = delta1Assembly.CreateInstance("Delta.D")!; delta1Instance.GetType().GetMethod("Write")!.Invoke(delta1Instance, new object[] { sb, "Test D1" }); var delta2Assembly = loader.LoadFromPath(_testFixture.DeltaPublicSigned2.Path); var delta2Instance = delta2Assembly.CreateInstance("Delta.D")!; delta2Instance.GetType().GetMethod("Write")!.Invoke(delta2Instance, new object[] { sb, "Test D2" }); var actual = sb.ToString(); Assert.Equal( @"Delta: Test D1 Delta.2: Test D2 ", actual); } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; if (ExecutionConditionUtil.IsCoreClr) { var ex = Assert.ThrowsAny<Exception>(() => analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb })); Assert.True(ex is MissingMethodException or TargetInvocationException, $@"Unexpected exception type: ""{ex.GetType()}"""); } else { analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal("42", sb.ToString()); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal(ExecutionConditionUtil.IsCoreClr ? "1" : "42", sb.ToString()); } [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))] public void AssemblyLoading_NativeDependency() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path); var analyzer = analyzerAssembly.CreateInstance("Class1")!; var result = analyzer.GetType().GetMethod("GetFileAttributes")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path }); Assert.Equal(0, Marshal.GetLastWin32Error()); Assert.Equal(FileAttributes.Archive, (FileAttributes)result!); } [Fact] public void AssemblyLoading_Delete() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); var tempDir = Temp.CreateDirectory(); var deltaCopy = tempDir.CreateFile("Delta.dll").CopyContentFrom(_testFixture.Delta1.Path); loader.AddDependencyLocation(deltaCopy.Path); Assembly delta = loader.LoadFromPath(deltaCopy.Path); try { File.Delete(deltaCopy.Path); } catch (UnauthorizedAccessException) { return; } // The above call may or may not throw depending on the platform configuration. // If it doesn't throw, we might as well check that things are still functioning reasonably. var d = delta.CreateInstance("Delta.D"); d!.GetType().GetMethod("Write")!.Invoke(d, new object[] { sb, "Test D" }); var actual = sb.ToString(); Assert.Equal( @"Delta: Test D ", actual); } #if NETCOREAPP [Fact] public void VerifyCompilerAssemblySimpleNames() { var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly; var caReferences = caAssembly.GetReferencedAssemblies(); var allReferenceSimpleNames = ArrayBuilder<string>.GetInstance(); allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in caReferences) { allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException()); } var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly; allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException()); var csReferences = csAssembly.GetReferencedAssemblies(); foreach (var reference in csReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly; var vbReferences = vbAssembly.GetReferencedAssemblies(); allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in vbReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames)) { allReferenceSimpleNames.Sort(); var allNames = string.Join(",\r\n ", allReferenceSimpleNames.Select(name => $@"""{name}""")); _output.WriteLine(" internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames ="); _output.WriteLine(" ImmutableHashSet.Create("); _output.WriteLine(" StringComparer.OrdinalIgnoreCase,"); _output.WriteLine($" {allNames});"); allReferenceSimpleNames.Free(); Assert.True(false, $"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it."); } else { allReferenceSimpleNames.Free(); } } [Fact] public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesSystemCollectionsImmutable() { // Create a separate ALC as the compiler context, load the compiler assembly and a modified version of S.C.I into it, // then use that to load and run `AssemblyLoadingInNonDefaultContextHelper1` below. We expect the analyzer running in // its own `DirectoryLoadContext` would use the bogus S.C.I loaded in the compiler load context instead of the real one // in the default context. var compilerContext = new System.Runtime.Loader.AssemblyLoadContext("compilerContext"); _ = compilerContext.LoadFromAssemblyPath(_testFixture.UserSystemCollectionsImmutable.Path); _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location); var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location); var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!, ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!; StringBuilder sb = new StringBuilder(); testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper1), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb }); Assert.Equal("42", sb.ToString()); } // This helper does the same thing as in `AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01` test above except the assertions. private void AssemblyLoadingInNonDefaultContextHelper1(StringBuilder sb) { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); } [Fact] public void AssemblyLoadingInNonDefaultContext_AnalyzerReferencesNonCompilerAssemblyUsedByDefaultContext() { // Load the V2 of Delta to default ALC, then create a separate ALC for compiler and load compiler assembly. // Next use compiler context to load and run `AssemblyLoadingInNonDefaultContextHelper2` below. We expect the analyzer running in // its own `DirectoryLoadContext` would load and use Delta V1 located in its directory instead of V2 already loaded in the default context. _ = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(_testFixture.Delta2.Path); var compilerContext = new System.Runtime.Loader.AssemblyLoadContext("compilerContext"); _ = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location); var testAssembly = compilerContext.LoadFromAssemblyPath(typeof(DefaultAnalyzerAssemblyLoaderTests).GetTypeInfo().Assembly.Location); var testObject = testAssembly.CreateInstance(typeof(DefaultAnalyzerAssemblyLoaderTests).FullName!, ignoreCase: false, BindingFlags.Default, binder: null, args: new object[] { _output, _testFixture }, null, null)!; StringBuilder sb = new StringBuilder(); testObject.GetType().GetMethod(nameof(AssemblyLoadingInNonDefaultContextHelper2), BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(testObject, new object[] { sb }); Assert.Equal( @"Delta: Hello ", sb.ToString()); } private void AssemblyLoadingInNonDefaultContextHelper2(StringBuilder sb) { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesDelta1.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesDelta1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); } #endif } }
1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerAssemblyLoader.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 System.Reflection; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract class AnalyzerAssemblyLoader : IAnalyzerAssemblyLoader { private readonly object _guard = new(); // lock _guard to read/write private readonly Dictionary<string, Assembly> _loadedAssembliesByPath = new(); private readonly Dictionary<string, AssemblyIdentity> _loadedAssemblyIdentitiesByPath = new(); private readonly Dictionary<AssemblyIdentity, Assembly> _loadedAssembliesByIdentity = new(); // maps file name to a full path (lock _guard to read/write): private readonly Dictionary<string, HashSet<string>> _knownAssemblyPathsBySimpleName = new(StringComparer.OrdinalIgnoreCase); protected abstract Assembly LoadFromPathImpl(string fullPath); #region Public API public void AddDependencyLocation(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); string simpleName = PathUtilities.GetFileName(fullPath, includeExtension: false); lock (_guard) { if (!_knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths)) { paths = new HashSet<string>(PathUtilities.Comparer); _knownAssemblyPathsBySimpleName.Add(simpleName, paths); } paths.Add(fullPath); } } public Assembly LoadFromPath(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); return LoadFromPathUnchecked(fullPath); } #endregion private Assembly LoadFromPathUnchecked(string fullPath) { return LoadFromPathUncheckedCore(fullPath); } private Assembly LoadFromPathUncheckedCore(string fullPath, AssemblyIdentity identity = null) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); // Check if we have already loaded an assembly with the same identity or from the given path. Assembly loadedAssembly = null; lock (_guard) { if (_loadedAssembliesByPath.TryGetValue(fullPath, out var existingAssembly)) { loadedAssembly = existingAssembly; } else { identity ??= GetOrAddAssemblyIdentity(fullPath); if (identity != null && _loadedAssembliesByIdentity.TryGetValue(identity, out existingAssembly)) { loadedAssembly = existingAssembly; } } } // Otherwise, load the assembly. if (loadedAssembly == null) { loadedAssembly = LoadFromPathImpl(fullPath); } // Add the loaded assembly to both path and identity cache. return AddToCache(loadedAssembly, fullPath, identity); } private Assembly AddToCache(Assembly assembly, string fullPath, AssemblyIdentity identity) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); Debug.Assert(assembly != null); identity = AddToCache(fullPath, identity ?? AssemblyIdentity.FromAssemblyDefinition(assembly)); Debug.Assert(identity != null); lock (_guard) { // The same assembly may be loaded from two different full paths (e.g. when loaded from GAC, etc.), // or another thread might have loaded the assembly after we checked above. if (_loadedAssembliesByIdentity.TryGetValue(identity, out var existingAssembly)) { assembly = existingAssembly; } else { _loadedAssembliesByIdentity.Add(identity, assembly); } // An assembly file might be replaced by another file with a different identity. // Last one wins. _loadedAssembliesByPath[fullPath] = assembly; return assembly; } } private AssemblyIdentity GetOrAddAssemblyIdentity(string fullPath) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); lock (_guard) { if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity)) { return existingIdentity; } } var identity = AssemblyIdentityUtils.TryGetAssemblyIdentity(fullPath); return AddToCache(fullPath, identity); } private AssemblyIdentity AddToCache(string fullPath, AssemblyIdentity identity) { lock (_guard) { if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity) && existingIdentity != null) { identity = existingIdentity; } else { _loadedAssemblyIdentitiesByPath[fullPath] = identity; } } return identity; } #nullable enable protected HashSet<string>? GetPaths(string simpleName) { _knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths); return paths; } /// <summary> /// When overridden in a derived class, allows substituting an assembly path after we've /// identified the context to load an assembly in, but before the assembly is actually /// loaded from disk. /// </summary> protected virtual string GetPathToLoad(string fullPath) { return fullPath; } #nullable disable public Assembly Load(string displayName) { if (!AssemblyIdentity.TryParseDisplayName(displayName, out var requestedIdentity)) { return null; } ImmutableArray<string> candidatePaths; lock (_guard) { // First, check if this loader already loaded the requested assembly: if (_loadedAssembliesByIdentity.TryGetValue(requestedIdentity, out var existingAssembly)) { return existingAssembly; } // Second, check if an assembly file of the same simple name was registered with the loader: if (!_knownAssemblyPathsBySimpleName.TryGetValue(requestedIdentity.Name, out var pathList)) { return null; } Debug.Assert(pathList.Count > 0); candidatePaths = pathList.ToImmutableArray(); } // Multiple assemblies of the same simple name but different identities might have been registered. // Load the one that matches the requested identity (if any). foreach (var candidatePath in candidatePaths) { var candidateIdentity = GetOrAddAssemblyIdentity(candidatePath); if (requestedIdentity.Equals(candidateIdentity)) { return LoadFromPathUncheckedCore(candidatePath, candidateIdentity); } } return 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 System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The base implementation for <see cref="IAnalyzerAssemblyLoader"/>. This type provides caching and tracking of inputs given /// to <see cref="AddDependencyLocation(string)"/>. /// </summary> /// <remarks> /// This type generally assumes that files on disk aren't changing, since it ensure that two calls to <see cref="LoadFromPath(string)"/> /// will always return the same thing, per that interface's contract. /// </remarks> internal abstract class AnalyzerAssemblyLoader : IAnalyzerAssemblyLoader { private readonly object _guard = new(); // lock _guard to read/write private readonly Dictionary<string, Assembly> _loadedAssembliesByPath = new(); // maps file name to a full path (lock _guard to read/write): private readonly Dictionary<string, ImmutableHashSet<string>> _knownAssemblyPathsBySimpleName = new(StringComparer.OrdinalIgnoreCase); /// <summary> /// Implemented by derived types to actually perform the load for an assembly that doesn't have a cached result. /// </summary> protected abstract Assembly LoadFromPathUncheckedImpl(string fullPath); #region Public API public void AddDependencyLocation(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); string simpleName = PathUtilities.GetFileName(fullPath, includeExtension: false); lock (_guard) { if (!_knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths)) { paths = ImmutableHashSet.Create(PathUtilities.Comparer, fullPath); _knownAssemblyPathsBySimpleName.Add(simpleName, paths); } else { _knownAssemblyPathsBySimpleName[simpleName] = paths.Add(fullPath); } } } public Assembly LoadFromPath(string fullPath) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); return LoadFromPathUnchecked(fullPath); } #endregion /// <summary> /// Returns the cached assembly for fullPath if we've done a load for this path before, or calls <see cref="LoadFromPathUncheckedImpl"/> if /// it needs to be loaded. This method skips the check in release builds that the path is an absolute path, hence the "Unchecked" in the name. /// </summary> protected Assembly LoadFromPathUnchecked(string fullPath) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); // Check if we have already loaded an assembly from the given path. Assembly? loadedAssembly = null; lock (_guard) { if (_loadedAssembliesByPath.TryGetValue(fullPath, out var existingAssembly)) { loadedAssembly = existingAssembly; } } // Otherwise, load the assembly. if (loadedAssembly == null) { loadedAssembly = LoadFromPathUncheckedImpl(fullPath); } // Add the loaded assembly to the path cache. lock (_guard) { _loadedAssembliesByPath[fullPath] = loadedAssembly; } return loadedAssembly; } protected ImmutableHashSet<string>? GetPaths(string simpleName) { lock (_guard) { _knownAssemblyPathsBySimpleName.TryGetValue(simpleName, out var paths); return paths; } } /// <summary> /// When overridden in a derived class, allows substituting an assembly path after we've /// identified the context to load an assembly in, but before the assembly is actually /// loaded from disk. This is used to substitute out the original path with the shadow-copied version. /// </summary> protected virtual string GetPathToLoad(string fullPath) { return fullPath; } } }
1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Core.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. #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.CodeAnalysis { internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { /// <summary> /// <p>Typically a user analyzer has a reference to the compiler and some of the compiler's /// dependencies such as System.Collections.Immutable. For the analyzer to correctly /// interoperate with the compiler that created it, we need to ensure that we always use the /// compiler's version of a given assembly over the analyzer's version.</p> /// /// <p>If we neglect to do this, then in the case where the user ships the compiler or its /// dependencies in the analyzer's bin directory, we could end up loading a separate /// instance of those assemblies in the process of loading the analyzer, which will surface /// as a failure to load the analyzer.</p> /// </summary> internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames = ImmutableHashSet.Create( StringComparer.OrdinalIgnoreCase, "Microsoft.CodeAnalysis", "Microsoft.CodeAnalysis.CSharp", "Microsoft.CodeAnalysis.VisualBasic", "System.Collections", "System.Collections.Concurrent", "System.Collections.Immutable", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.StackTrace", "System.Diagnostics.Tracing", "System.IO.Compression", "System.IO.FileSystem", "System.Linq", "System.Linq.Expressions", "System.Memory", "System.Reflection.Metadata", "System.Reflection.Primitives", "System.Resources.ResourceManager", "System.Runtime", "System.Runtime.CompilerServices.Unsafe", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Runtime.Loader", "System.Runtime.Numerics", "System.Runtime.Serialization.Primitives", "System.Security.Cryptography.Algorithms", "System.Security.Cryptography.Primitives", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.Threading.ThreadPool", "System.Xml.ReaderWriter", "System.Xml.XDocument", "System.Xml.XPath.XDocument"); internal virtual ImmutableHashSet<string> AssemblySimpleNamesToBeLoadedInCompilerContext => CompilerAssemblySimpleNames; // This is the context where compiler (and some of its dependencies) are being loaded into, which might be different from AssemblyLoadContext.Default. private static readonly AssemblyLoadContext s_compilerLoadContext = AssemblyLoadContext.GetLoadContext(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly)!; private readonly object _guard = new object(); private readonly Dictionary<string, DirectoryLoadContext> _loadContextByDirectory = new Dictionary<string, DirectoryLoadContext>(StringComparer.Ordinal); protected override Assembly LoadFromPathImpl(string fullPath) { DirectoryLoadContext? loadContext; var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath)); lock (_guard) { if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext)) { loadContext = new DirectoryLoadContext(fullDirectoryPath, this, s_compilerLoadContext); _loadContextByDirectory[fullDirectoryPath] = loadContext; } } var name = AssemblyName.GetAssemblyName(fullPath); return loadContext.LoadFromAssemblyName(name); } internal static class TestAccessor { public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader) { return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray(); } } private sealed class DirectoryLoadContext : AssemblyLoadContext { internal string Directory { get; } private readonly DefaultAnalyzerAssemblyLoader _loader; private readonly AssemblyLoadContext _compilerLoadContext; public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader, AssemblyLoadContext compilerLoadContext) { Directory = directory; _loader = loader; _compilerLoadContext = compilerLoadContext; } protected override Assembly? Load(AssemblyName assemblyName) { var simpleName = assemblyName.Name!; if (_loader.AssemblySimpleNamesToBeLoadedInCompilerContext.Contains(simpleName)) { // Delegate to the compiler's load context to load the compiler or anything // referenced by the compiler return _compilerLoadContext.LoadFromAssemblyName(assemblyName); } var assemblyPath = Path.Combine(Directory, simpleName + ".dll"); var paths = _loader.GetPaths(simpleName); if (paths is null) { // The analyzer didn't explicitly register this dependency. Most likely the // assembly we're trying to load here is netstandard or a similar framework // assembly. In this case, we want to load it in compiler's ALC to avoid any // potential type mismatch issue. Otherwise, if this is truly an unknown assembly, // we assume both compiler and default ALC will fail to load it. return _compilerLoadContext.LoadFromAssemblyName(assemblyName); } Debug.Assert(paths.Any()); // A matching assembly in this directory was specified via /analyzer. if (paths.Contains(assemblyPath)) { return LoadFromAssemblyPath(_loader.GetPathToLoad(assemblyPath)); } AssemblyName? bestCandidateName = null; string? bestCandidatePath = null; // The assembly isn't expected to be found at 'assemblyPath', // but some assembly with the same simple name is known to the loader. foreach (var candidatePath in paths) { // Note: we assume that the assembly really can be found at 'candidatePath' // (without 'GetPathToLoad'), and that calling GetAssemblyName doesn't cause us // to hold a lock on the file. This prevents unnecessary shadow copies. var candidateName = AssemblyName.GetAssemblyName(candidatePath); // Checking FullName ensures that version and PublicKeyToken match exactly. if (candidateName.FullName.Equals(assemblyName.FullName, StringComparison.OrdinalIgnoreCase)) { return LoadFromAssemblyPath(_loader.GetPathToLoad(candidatePath)); } else if (bestCandidateName is null || bestCandidateName.Version < candidateName.Version) { bestCandidateName = candidateName; bestCandidatePath = candidatePath; } } Debug.Assert(bestCandidateName != null); Debug.Assert(bestCandidatePath != null); return LoadFromAssemblyPath(_loader.GetPathToLoad(bestCandidatePath)); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var assemblyPath = Path.Combine(Directory, unmanagedDllName + ".dll"); var paths = _loader.GetPaths(unmanagedDllName); if (paths is null || !paths.Contains(assemblyPath)) { return IntPtr.Zero; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadUnmanagedDllFromPath(pathToLoad); } } } } #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. #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace Microsoft.CodeAnalysis { internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { /// <summary> /// <p>Typically a user analyzer has a reference to the compiler and some of the compiler's /// dependencies such as System.Collections.Immutable. For the analyzer to correctly /// interoperate with the compiler that created it, we need to ensure that we always use the /// compiler's version of a given assembly over the analyzer's version.</p> /// /// <p>If we neglect to do this, then in the case where the user ships the compiler or its /// dependencies in the analyzer's bin directory, we could end up loading a separate /// instance of those assemblies in the process of loading the analyzer, which will surface /// as a failure to load the analyzer.</p> /// </summary> internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames = ImmutableHashSet.Create( StringComparer.OrdinalIgnoreCase, "Microsoft.CodeAnalysis", "Microsoft.CodeAnalysis.CSharp", "Microsoft.CodeAnalysis.VisualBasic", "System.Collections", "System.Collections.Concurrent", "System.Collections.Immutable", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.StackTrace", "System.Diagnostics.Tracing", "System.IO.Compression", "System.IO.FileSystem", "System.Linq", "System.Linq.Expressions", "System.Memory", "System.Reflection.Metadata", "System.Reflection.Primitives", "System.Resources.ResourceManager", "System.Runtime", "System.Runtime.CompilerServices.Unsafe", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Runtime.Loader", "System.Runtime.Numerics", "System.Runtime.Serialization.Primitives", "System.Security.Cryptography.Algorithms", "System.Security.Cryptography.Primitives", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.Threading.ThreadPool", "System.Xml.ReaderWriter", "System.Xml.XDocument", "System.Xml.XPath.XDocument"); internal virtual ImmutableHashSet<string> AssemblySimpleNamesToBeLoadedInCompilerContext => CompilerAssemblySimpleNames; // This is the context where compiler (and some of its dependencies) are being loaded into, which might be different from AssemblyLoadContext.Default. private static readonly AssemblyLoadContext s_compilerLoadContext = AssemblyLoadContext.GetLoadContext(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly)!; private readonly object _guard = new object(); private readonly Dictionary<string, DirectoryLoadContext> _loadContextByDirectory = new Dictionary<string, DirectoryLoadContext>(StringComparer.Ordinal); protected override Assembly LoadFromPathUncheckedImpl(string fullPath) { DirectoryLoadContext? loadContext; var fullDirectoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException(message: null, paramName: nameof(fullPath)); lock (_guard) { if (!_loadContextByDirectory.TryGetValue(fullDirectoryPath, out loadContext)) { loadContext = new DirectoryLoadContext(fullDirectoryPath, this, s_compilerLoadContext); _loadContextByDirectory[fullDirectoryPath] = loadContext; } } var name = AssemblyName.GetAssemblyName(fullPath); return loadContext.LoadFromAssemblyName(name); } internal static class TestAccessor { public static AssemblyLoadContext[] GetOrderedLoadContexts(DefaultAnalyzerAssemblyLoader loader) { return loader._loadContextByDirectory.Values.OrderBy(v => v.Directory).ToArray(); } } private sealed class DirectoryLoadContext : AssemblyLoadContext { internal string Directory { get; } private readonly DefaultAnalyzerAssemblyLoader _loader; private readonly AssemblyLoadContext _compilerLoadContext; public DirectoryLoadContext(string directory, DefaultAnalyzerAssemblyLoader loader, AssemblyLoadContext compilerLoadContext) { Directory = directory; _loader = loader; _compilerLoadContext = compilerLoadContext; } protected override Assembly? Load(AssemblyName assemblyName) { var simpleName = assemblyName.Name!; if (_loader.AssemblySimpleNamesToBeLoadedInCompilerContext.Contains(simpleName)) { // Delegate to the compiler's load context to load the compiler or anything // referenced by the compiler return _compilerLoadContext.LoadFromAssemblyName(assemblyName); } var assemblyPath = Path.Combine(Directory, simpleName + ".dll"); var paths = _loader.GetPaths(simpleName); if (paths is null) { // The analyzer didn't explicitly register this dependency. Most likely the // assembly we're trying to load here is netstandard or a similar framework // assembly. In this case, we want to load it in compiler's ALC to avoid any // potential type mismatch issue. Otherwise, if this is truly an unknown assembly, // we assume both compiler and default ALC will fail to load it. return _compilerLoadContext.LoadFromAssemblyName(assemblyName); } Debug.Assert(paths.Any()); // A matching assembly in this directory was specified via /analyzer. if (paths.Contains(assemblyPath)) { return LoadFromAssemblyPath(_loader.GetPathToLoad(assemblyPath)); } AssemblyName? bestCandidateName = null; string? bestCandidatePath = null; // The assembly isn't expected to be found at 'assemblyPath', // but some assembly with the same simple name is known to the loader. foreach (var candidatePath in paths) { // Note: we assume that the assembly really can be found at 'candidatePath' // (without 'GetPathToLoad'), and that calling GetAssemblyName doesn't cause us // to hold a lock on the file. This prevents unnecessary shadow copies. var candidateName = AssemblyName.GetAssemblyName(candidatePath); // Checking FullName ensures that version and PublicKeyToken match exactly. if (candidateName.FullName.Equals(assemblyName.FullName, StringComparison.OrdinalIgnoreCase)) { return LoadFromAssemblyPath(_loader.GetPathToLoad(candidatePath)); } else if (bestCandidateName is null || bestCandidateName.Version < candidateName.Version) { bestCandidateName = candidateName; bestCandidatePath = candidatePath; } } Debug.Assert(bestCandidateName != null); Debug.Assert(bestCandidatePath != null); return LoadFromAssemblyPath(_loader.GetPathToLoad(bestCandidatePath)); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var assemblyPath = Path.Combine(Directory, unmanagedDllName + ".dll"); var paths = _loader.GetPaths(unmanagedDllName); if (paths is null || !paths.Contains(assemblyPath)) { return IntPtr.Zero; } var pathToLoad = _loader.GetPathToLoad(assemblyPath); return LoadUnmanagedDllFromPath(pathToLoad); } } } } #endif
1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Desktop.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 #if !NETCOREAPP using System; using System.Reflection; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Loads analyzer assemblies from their original locations in the file system. /// Assemblies will only be loaded from the locations specified when the loader /// is instantiated. /// </summary> /// <remarks> /// This type is meant to be used in scenarios where it is OK for the analyzer /// assemblies to be locked on disk for the lifetime of the host; for example, /// csc.exe and vbc.exe. In scenarios where support for updating or deleting /// the analyzer on disk is required a different loader should be used. /// </remarks> internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { private int _hookedAssemblyResolve; protected override Assembly LoadFromPathImpl(string fullPath) { if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0) { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } var pathToLoad = GetPathToLoad(fullPath); return Assembly.LoadFrom(pathToLoad); } private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { try { return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } catch { return null; } } } } #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. #if !NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Loads analyzer assemblies from their original locations in the file system. /// Assemblies will only be loaded from the locations specified when the loader /// is instantiated. /// </summary> /// <remarks> /// This type is meant to be used in scenarios where it is OK for the analyzer /// assemblies to be locked on disk for the lifetime of the host; for example, /// csc.exe and vbc.exe. In scenarios where support for updating or deleting /// the analyzer on disk is required a different loader should be used. /// </remarks> internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { private readonly object _guard = new(); private readonly Dictionary<AssemblyIdentity, Assembly> _loadedAssembliesByIdentity = new(); private readonly Dictionary<string, AssemblyIdentity?> _loadedAssemblyIdentitiesByPath = new(); private int _hookedAssemblyResolve; protected override Assembly LoadFromPathUncheckedImpl(string fullPath) { if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0) { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } AssemblyIdentity? identity; lock (_guard) { identity = GetOrAddAssemblyIdentity(fullPath); if (identity != null && _loadedAssembliesByIdentity.TryGetValue(identity, out var existingAssembly)) { return existingAssembly; } } var pathToLoad = GetPathToLoad(fullPath); var loadedAssembly = Assembly.LoadFrom(pathToLoad); lock (_guard) { identity ??= identity ?? AssemblyIdentity.FromAssemblyDefinition(loadedAssembly); // The same assembly may be loaded from two different full paths (e.g. when loaded from GAC, etc.), // or another thread might have loaded the assembly after we checked above. if (_loadedAssembliesByIdentity.TryGetValue(identity, out var existingAssembly)) { loadedAssembly = existingAssembly; } else { _loadedAssembliesByIdentity.Add(identity, loadedAssembly); } return loadedAssembly; } } private Assembly? CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { // In the .NET Framework, if a handler to AssemblyResolve throws an exception, other handlers // are not called. To avoid any bug in our handler breaking other handlers running in the same process // we catch exceptions here. We do not expect exceptions to be thrown though. try { return GetOrLoad(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } catch { return null; } } private AssemblyIdentity? GetOrAddAssemblyIdentity(string fullPath) { Debug.Assert(PathUtilities.IsAbsolute(fullPath)); lock (_guard) { if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity)) { return existingIdentity; } } var identity = AssemblyIdentityUtils.TryGetAssemblyIdentity(fullPath); lock (_guard) { if (_loadedAssemblyIdentitiesByPath.TryGetValue(fullPath, out var existingIdentity) && existingIdentity != null) { // Somebody else beat us, so used the cached value identity = existingIdentity; } else { _loadedAssemblyIdentitiesByPath[fullPath] = identity; } } return identity; } private Assembly? GetOrLoad(string displayName) { if (!AssemblyIdentity.TryParseDisplayName(displayName, out var requestedIdentity)) { return null; } ImmutableHashSet<string> candidatePaths; lock (_guard) { // First, check if this loader already loaded the requested assembly: if (_loadedAssembliesByIdentity.TryGetValue(requestedIdentity, out var existingAssembly)) { return existingAssembly; } // Second, check if an assembly file of the same simple name was registered with the loader: candidatePaths = GetPaths(requestedIdentity.Name); if (candidatePaths is null) { return null; } Debug.Assert(candidatePaths.Count > 0); } // Find the highest version that satisfies the original request. We'll match for the highest version we can, assuming it // actually matches the original request string? bestPath = null; Version? bestIdentityVersion = null; // Sort the candidate paths by ordinal, to ensure determinism with the same inputs if you were to have multiple assemblies // providing the same version. foreach (var candidatePath in candidatePaths.OrderBy(StringComparer.Ordinal)) { var candidateIdentity = GetOrAddAssemblyIdentity(candidatePath); if (candidateIdentity is not null && candidateIdentity.Version >= requestedIdentity.Version && candidateIdentity.PublicKeyToken.SequenceEqual(requestedIdentity.PublicKeyToken)) { if (bestIdentityVersion is null || candidateIdentity.Version > bestIdentityVersion) { bestPath = candidatePath; bestIdentityVersion = candidateIdentity.Version; } } } if (bestPath != null) { return LoadFromPathUnchecked(bestPath); } return null; } } } #endif
1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/Portable/DiagnosticAnalyzer/ShadowCopyAnalyzerAssemblyLoader.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.Reflection; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal sealed class ShadowCopyAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader { /// <summary> /// The base directory for shadow copies. Each instance of /// <see cref="ShadowCopyAnalyzerAssemblyLoader"/> gets its own /// subdirectory under this directory. This is also the starting point /// for scavenge operations. /// </summary> private readonly string _baseDirectory; internal readonly Task DeleteLeftoverDirectoriesTask; /// <summary> /// The directory where this instance of <see cref="ShadowCopyAnalyzerAssemblyLoader"/> /// will shadow-copy assemblies, and the mutex created to mark that the owner of it is still active. /// </summary> private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex; /// <summary> /// Used to generate unique names for per-assembly directories. Should be updated with <see cref="Interlocked.Increment(ref int)"/>. /// </summary> private int _assemblyDirectoryId; public ShadowCopyAnalyzerAssemblyLoader(string baseDirectory = null) { if (baseDirectory != null) { _baseDirectory = baseDirectory; } else { _baseDirectory = Path.Combine(Path.GetTempPath(), "CodeAnalysis", "AnalyzerShadowCopies"); } _shadowCopyDirectoryAndMutex = new Lazy<(string directory, Mutex)>( () => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication); DeleteLeftoverDirectoriesTask = Task.Run(DeleteLeftoverDirectories); } private void DeleteLeftoverDirectories() { // Avoid first chance exception if (!Directory.Exists(_baseDirectory)) return; IEnumerable<string> subDirectories; try { subDirectories = Directory.EnumerateDirectories(_baseDirectory); } catch (DirectoryNotFoundException) { return; } foreach (var subDirectory in subDirectories) { string name = Path.GetFileName(subDirectory).ToLowerInvariant(); Mutex mutex = null; try { // We only want to try deleting the directory if no-one else is currently // using it. That is, if there is no corresponding mutex. if (!Mutex.TryOpenExisting(name, out mutex)) { ClearReadOnlyFlagOnFiles(subDirectory); Directory.Delete(subDirectory, recursive: true); } } catch { // If something goes wrong we will leave it to the next run to clean up. // Just swallow the exception and move on. } finally { if (mutex != null) { mutex.Dispose(); } } } } #nullable enable protected override string GetPathToLoad(string fullPath) { string assemblyDirectory = CreateUniqueDirectoryForAssembly(); string shadowCopyPath = CopyFileAndResources(fullPath, assemblyDirectory); return shadowCopyPath; } #nullable disable private static string CopyFileAndResources(string fullPath, string assemblyDirectory) { string fileNameWithExtension = Path.GetFileName(fullPath); string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension); CopyFile(fullPath, shadowCopyPath); string originalDirectory = Path.GetDirectoryName(fullPath); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension); string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources"; string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll"; foreach (var directory in Directory.EnumerateDirectories(originalDirectory)) { string directoryName = Path.GetFileName(directory); string resourcesPath = Path.Combine(directory, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } } return shadowCopyPath; } private static void CopyFile(string originalPath, string shadowCopyPath) { var directory = Path.GetDirectoryName(shadowCopyPath); Directory.CreateDirectory(directory); File.Copy(originalPath, shadowCopyPath); ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath)); } private static void ClearReadOnlyFlagOnFiles(string directoryPath) { DirectoryInfo directory = new DirectoryInfo(directoryPath); foreach (var file in directory.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories)) { ClearReadOnlyFlagOnFile(file); } } private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo) { try { if (fileInfo.IsReadOnly) { fileInfo.IsReadOnly = false; } } catch { // There are many reasons this could fail. Ignore it and keep going. } } private string CreateUniqueDirectoryForAssembly() { int directoryId = Interlocked.Increment(ref _assemblyDirectoryId); string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, directoryId.ToString()); Directory.CreateDirectory(directory); return directory; } private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess() { string guid = Guid.NewGuid().ToString("N").ToLowerInvariant(); string directory = Path.Combine(_baseDirectory, guid); var mutex = new Mutex(initiallyOwned: false, name: guid); Directory.CreateDirectory(directory); return (directory, mutex); } } }
// 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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal sealed class ShadowCopyAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader { /// <summary> /// The base directory for shadow copies. Each instance of /// <see cref="ShadowCopyAnalyzerAssemblyLoader"/> gets its own /// subdirectory under this directory. This is also the starting point /// for scavenge operations. /// </summary> private readonly string _baseDirectory; internal readonly Task DeleteLeftoverDirectoriesTask; /// <summary> /// The directory where this instance of <see cref="ShadowCopyAnalyzerAssemblyLoader"/> /// will shadow-copy assemblies, and the mutex created to mark that the owner of it is still active. /// </summary> private readonly Lazy<(string directory, Mutex)> _shadowCopyDirectoryAndMutex; /// <summary> /// Used to generate unique names for per-assembly directories. Should be updated with <see cref="Interlocked.Increment(ref int)"/>. /// </summary> private int _assemblyDirectoryId; public ShadowCopyAnalyzerAssemblyLoader(string? baseDirectory = null) { if (baseDirectory != null) { _baseDirectory = baseDirectory; } else { _baseDirectory = Path.Combine(Path.GetTempPath(), "CodeAnalysis", "AnalyzerShadowCopies"); } _shadowCopyDirectoryAndMutex = new Lazy<(string directory, Mutex)>( () => CreateUniqueDirectoryForProcess(), LazyThreadSafetyMode.ExecutionAndPublication); DeleteLeftoverDirectoriesTask = Task.Run(DeleteLeftoverDirectories); } private void DeleteLeftoverDirectories() { // Avoid first chance exception if (!Directory.Exists(_baseDirectory)) return; IEnumerable<string> subDirectories; try { subDirectories = Directory.EnumerateDirectories(_baseDirectory); } catch (DirectoryNotFoundException) { return; } foreach (var subDirectory in subDirectories) { string name = Path.GetFileName(subDirectory).ToLowerInvariant(); Mutex? mutex = null; try { // We only want to try deleting the directory if no-one else is currently // using it. That is, if there is no corresponding mutex. if (!Mutex.TryOpenExisting(name, out mutex)) { ClearReadOnlyFlagOnFiles(subDirectory); Directory.Delete(subDirectory, recursive: true); } } catch { // If something goes wrong we will leave it to the next run to clean up. // Just swallow the exception and move on. } finally { if (mutex != null) { mutex.Dispose(); } } } } protected override string GetPathToLoad(string fullPath) { string assemblyDirectory = CreateUniqueDirectoryForAssembly(); string shadowCopyPath = CopyFileAndResources(fullPath, assemblyDirectory); return shadowCopyPath; } private static string CopyFileAndResources(string fullPath, string assemblyDirectory) { string fileNameWithExtension = Path.GetFileName(fullPath); string shadowCopyPath = Path.Combine(assemblyDirectory, fileNameWithExtension); CopyFile(fullPath, shadowCopyPath); string originalDirectory = Path.GetDirectoryName(fullPath)!; string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileNameWithExtension); string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources"; string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll"; foreach (var directory in Directory.EnumerateDirectories(originalDirectory)) { string directoryName = Path.GetFileName(directory); string resourcesPath = Path.Combine(directory, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } resourcesPath = Path.Combine(directory, resourcesNameWithoutExtension, resourcesNameWithExtension); if (File.Exists(resourcesPath)) { string resourcesShadowCopyPath = Path.Combine(assemblyDirectory, directoryName, resourcesNameWithoutExtension, resourcesNameWithExtension); CopyFile(resourcesPath, resourcesShadowCopyPath); } } return shadowCopyPath; } private static void CopyFile(string originalPath, string shadowCopyPath) { var directory = Path.GetDirectoryName(shadowCopyPath); Directory.CreateDirectory(directory); File.Copy(originalPath, shadowCopyPath); ClearReadOnlyFlagOnFile(new FileInfo(shadowCopyPath)); } private static void ClearReadOnlyFlagOnFiles(string directoryPath) { DirectoryInfo directory = new DirectoryInfo(directoryPath); foreach (var file in directory.EnumerateFiles(searchPattern: "*", searchOption: SearchOption.AllDirectories)) { ClearReadOnlyFlagOnFile(file); } } private static void ClearReadOnlyFlagOnFile(FileInfo fileInfo) { try { if (fileInfo.IsReadOnly) { fileInfo.IsReadOnly = false; } } catch { // There are many reasons this could fail. Ignore it and keep going. } } private string CreateUniqueDirectoryForAssembly() { int directoryId = Interlocked.Increment(ref _assemblyDirectoryId); string directory = Path.Combine(_shadowCopyDirectoryAndMutex.Value.directory, directoryId.ToString()); Directory.CreateDirectory(directory); return directory; } private (string directory, Mutex mutex) CreateUniqueDirectoryForProcess() { string guid = Guid.NewGuid().ToString("N").ToLowerInvariant(); string directory = Path.Combine(_baseDirectory, guid); var mutex = new Mutex(initiallyOwned: false, name: guid); Directory.CreateDirectory(directory); return (directory, mutex); } } }
1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Test/Core/AssemblyLoadTestFixture.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.Linq; using Basic.Reference.Assemblies; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Test.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class AssemblyLoadTestFixture : IDisposable { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: Diagnostic.MaxWarningLevel); private readonly TempRoot _temp; private readonly TempDirectory _directory; public TempFile Delta1 { get; } public TempFile Gamma { get; } public TempFile Beta { get; } public TempFile Alpha { get; } public TempFile Delta2 { get; } public TempFile Epsilon { get; } public TempFile Delta2B { get; } public TempFile Delta3 { get; } public TempFile UserSystemCollectionsImmutable { get; } /// <summary> /// An analyzer which uses members in its referenced version of System.Collections.Immutable /// that are not present in the compiler's version of System.Collections.Immutable. /// </summary> public TempFile AnalyzerReferencesSystemCollectionsImmutable1 { get; } /// <summary> /// An analyzer which uses members in its referenced version of System.Collections.Immutable /// which have different behavior than the same members in compiler's version of System.Collections.Immutable. /// </summary> public TempFile AnalyzerReferencesSystemCollectionsImmutable2 { get; } public TempFile AnalyzerReferencesDelta1 { get; } public TempFile FaultyAnalyzer { get; } public TempFile AnalyzerWithDependency { get; } public TempFile AnalyzerDependency { get; } public TempFile AnalyzerWithNativeDependency { get; } public AssemblyLoadTestFixture() { _temp = new TempRoot(); _directory = _temp.CreateDirectory(); Delta1 = GenerateDll("Delta", _directory, @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta: "" + s); } } } "); var delta1Reference = MetadataReference.CreateFromFile(Delta1.Path); Gamma = GenerateDll("Gamma", _directory, @" using System.Text; using Delta; namespace Gamma { public class G { public void Write(StringBuilder sb, string s) { D d = new D(); d.Write(sb, ""Gamma: "" + s); } } } ", delta1Reference); var gammaReference = MetadataReference.CreateFromFile(Gamma.Path); Beta = GenerateDll("Beta", _directory, @" using System.Text; using Gamma; namespace Beta { public class B { public void Write(StringBuilder sb, string s) { G g = new G(); g.Write(sb, ""Beta: "" + s); } } } ", gammaReference); Alpha = GenerateDll("Alpha", _directory, @" using System.Text; using Gamma; namespace Alpha { public class A { public void Write(StringBuilder sb, string s) { G g = new G(); g.Write(sb, ""Alpha: "" + s); } } } ", gammaReference); var v2Directory = _directory.CreateDirectory("Version2"); Delta2 = GenerateDll("Delta", v2Directory, @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta.2: "" + s); } } } "); var delta2Reference = MetadataReference.CreateFromFile(Delta2.Path); Epsilon = GenerateDll("Epsilon", v2Directory, @" using System.Text; using Delta; namespace Epsilon { public class E { public void Write(StringBuilder sb, string s) { D d = new D(); d.Write(sb, ""Epsilon: "" + s); } } } ", delta2Reference); var v2BDirectory = _directory.CreateDirectory("Version2B"); Delta2B = GenerateDll("Delta", v2BDirectory, @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta.2B: "" + s); } } } "); var v3Directory = _directory.CreateDirectory("Version3"); Delta3 = GenerateDll("Delta", v3Directory, @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta.3: "" + s); } } } "); var sciUserDirectory = _directory.CreateDirectory("SCIUser"); var compilerReference = MetadataReference.CreateFromFile(typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly.Location); UserSystemCollectionsImmutable = GenerateDll("System.Collections.Immutable", sciUserDirectory, @" namespace System.Collections.Immutable { public static class ImmutableArray { public static ImmutableArray<T> Create<T>(T t) => new(); } public struct ImmutableArray<T> { public int Length => 42; public static int MyMethod() => 42; } } ", compilerReference); var userSystemCollectionsImmutableReference = MetadataReference.CreateFromFile(UserSystemCollectionsImmutable.Path); AnalyzerReferencesSystemCollectionsImmutable1 = GenerateDll("AnalyzerUsesSystemCollectionsImmutable1", sciUserDirectory, @" using System.Text; using System.Collections.Immutable; public class Analyzer { public void Method(StringBuilder sb) { sb.Append(ImmutableArray<object>.MyMethod()); } } ", userSystemCollectionsImmutableReference, compilerReference); AnalyzerReferencesSystemCollectionsImmutable2 = GenerateDll("AnalyzerUsesSystemCollectionsImmutable2", sciUserDirectory, @" using System.Text; using System.Collections.Immutable; public class Analyzer { public void Method(StringBuilder sb) { sb.Append(ImmutableArray.Create(""a"").Length); } } ", userSystemCollectionsImmutableReference, compilerReference); var analyzerReferencesDelta1Directory = _directory.CreateDirectory("AnalyzerReferencesDelta1"); var delta1InAnalyzerReferencesDelta1 = analyzerReferencesDelta1Directory.CopyFile(Delta1.Path); AnalyzerReferencesDelta1 = GenerateDll("AnalyzerReferencesDelta1", _directory, @" using System.Text; using Delta; public class Analyzer { public void Method(StringBuilder sb) { var d = new D(); d.Write(sb, ""Hello""); } } ", MetadataReference.CreateFromFile(delta1InAnalyzerReferencesDelta1.Path), compilerReference); var faultyAnalyzerDirectory = _directory.CreateDirectory("FaultyAnalyzer"); FaultyAnalyzer = GenerateDll("FaultyAnalyzer", faultyAnalyzerDirectory, @" using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public abstract class TestAnalyzer : DiagnosticAnalyzer { } ", compilerReference); var realSciReference = MetadataReference.CreateFromFile(typeof(ImmutableArray).Assembly.Location); var analyzerWithDependencyDirectory = _directory.CreateDirectory("AnalyzerWithDependency"); AnalyzerDependency = GenerateDll("AnalyzerDependency", analyzerWithDependencyDirectory, @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; public abstract class AbstractTestAnalyzer : DiagnosticAnalyzer { protected static string SomeString = nameof(SomeString); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } ", realSciReference, compilerReference); AnalyzerWithDependency = GenerateDll("Analyzer", analyzerWithDependencyDirectory, @" using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class TestAnalyzer : AbstractTestAnalyzer { private static string SomeString2 = AbstractTestAnalyzer.SomeString; }", realSciReference, compilerReference, MetadataReference.CreateFromFile(AnalyzerDependency.Path)); AnalyzerWithNativeDependency = GenerateDll("AnalyzerWithNativeDependency", _directory, @" using System; using System.Runtime.InteropServices; public class Class1 { [DllImport(""kernel32.dll"", CharSet = CharSet.Unicode, SetLastError = true)] private static extern int GetFileAttributesW(string lpFileName); public int GetFileAttributes(string path) { return GetFileAttributesW(path); } } "); } private static TempFile GenerateDll(string assemblyName, TempDirectory directory, string csSource, params MetadataReference[] additionalReferences) { var analyzerDependencyCompilation = CSharpCompilation.Create( assemblyName: assemblyName, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(csSource) }, references: new MetadataReference[] { NetStandard20.mscorlib, NetStandard20.netstandard, NetStandard20.SystemRuntime }.Concat(additionalReferences), options: s_dllWithMaxWarningLevel); var tempFile = directory.CreateFile($"{assemblyName}.dll"); tempFile.WriteAllBytes(analyzerDependencyCompilation.EmitToArray()); return tempFile; } public void Dispose() { _temp.Dispose(); } } }
// 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.Linq; using Basic.Reference.Assemblies; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Test.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class AssemblyLoadTestFixture : IDisposable { private readonly TempRoot _temp; private readonly TempDirectory _directory; /// <summary> /// An assembly with no references, assembly version 1. /// </summary> public TempFile Delta1 { get; } /// <summary> /// An assembly with no references, assembly version 1, and public signed. /// </summary> public TempFile DeltaPublicSigned1 { get; } /// <summary> /// An assembly with a reference to <see cref="Delta1"/>. /// </summary> public TempFile Gamma { get; } /// <summary> /// An assembly with a reference to <see cref="DeltaPublicSigned1"/>. /// </summary> public TempFile GammaReferencingPublicSigned { get; } /// <summary> /// An assembly with a reference to <see cref="Gamma"/>. /// </summary> public TempFile Beta { get; } /// <summary> /// An assembly with a reference to <see cref="Gamma"/>. /// </summary> public TempFile Alpha { get; } /// <summary> /// An assembly with no references, assembly version 2. /// </summary> public TempFile Delta2 { get; } /// <summary> /// An assembly with no references, assembly version 2, and public signed. /// </summary> public TempFile DeltaPublicSigned2 { get; } /// <summary> /// An assembly with a reference to <see cref="Delta2"/>. /// </summary> public TempFile Epsilon { get; } /// <summary> /// An assembly with a reference to <see cref="DeltaPublicSigned2"/>. /// </summary> public TempFile EpsilonReferencingPublicSigned { get; } /// <summary> /// An assembly with no references, assembly version 2. The implementation however is different than /// <see cref="Delta2"/> so we can test having two assemblies that look the same but aren't. /// </summary> public TempFile Delta2B { get; } /// <summary> /// An assembly with no references, assembly version 3. /// </summary> public TempFile Delta3 { get; } public TempFile UserSystemCollectionsImmutable { get; } /// <summary> /// An analyzer which uses members in its referenced version of System.Collections.Immutable /// that are not present in the compiler's version of System.Collections.Immutable. /// </summary> public TempFile AnalyzerReferencesSystemCollectionsImmutable1 { get; } /// <summary> /// An analyzer which uses members in its referenced version of System.Collections.Immutable /// which have different behavior than the same members in compiler's version of System.Collections.Immutable. /// </summary> public TempFile AnalyzerReferencesSystemCollectionsImmutable2 { get; } public TempFile AnalyzerReferencesDelta1 { get; } public TempFile FaultyAnalyzer { get; } public TempFile AnalyzerWithDependency { get; } public TempFile AnalyzerDependency { get; } public TempFile AnalyzerWithNativeDependency { get; } public AssemblyLoadTestFixture() { _temp = new TempRoot(); _directory = _temp.CreateDirectory(); const string Delta1Source = @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta: "" + s); } } } "; Delta1 = GenerateDll("Delta", _directory, Delta1Source); var delta1Reference = MetadataReference.CreateFromFile(Delta1.Path); DeltaPublicSigned1 = GenerateDll("DeltaPublicSigned", _directory.CreateDirectory("Delta1PublicSigned"), Delta1Source, publicSign: true); const string GammaSource = @" using System.Text; using Delta; namespace Gamma { public class G { public void Write(StringBuilder sb, string s) { D d = new D(); d.Write(sb, ""Gamma: "" + s); } } } "; Gamma = GenerateDll("Gamma", _directory, GammaSource, delta1Reference); GammaReferencingPublicSigned = GenerateDll("GammaReferencingPublicSigned", _directory.CreateDirectory("GammaReferencingPublicSigned"), GammaSource, MetadataReference.CreateFromFile(DeltaPublicSigned1.Path)); var gammaReference = MetadataReference.CreateFromFile(Gamma.Path); Beta = GenerateDll("Beta", _directory, @" using System.Text; using Gamma; namespace Beta { public class B { public void Write(StringBuilder sb, string s) { G g = new G(); g.Write(sb, ""Beta: "" + s); } } } ", gammaReference); Alpha = GenerateDll("Alpha", _directory, @" using System.Text; using Gamma; namespace Alpha { public class A { public void Write(StringBuilder sb, string s) { G g = new G(); g.Write(sb, ""Alpha: "" + s); } } } ", gammaReference); const string Delta2Source = @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta.2: "" + s); } } } "; var v2Directory = _directory.CreateDirectory("Version2"); Delta2 = GenerateDll("Delta", v2Directory, Delta2Source); var v2PublicSignedDirectory = _directory.CreateDirectory("Version2PublicSigned"); DeltaPublicSigned2 = GenerateDll("DeltaPublicSigned", v2PublicSignedDirectory, Delta2Source, publicSign: true); var delta2Reference = MetadataReference.CreateFromFile(Delta2.Path); const string EpsilonSource = @" using System.Text; using Delta; namespace Epsilon { public class E { public void Write(StringBuilder sb, string s) { D d = new D(); d.Write(sb, ""Epsilon: "" + s); } } } "; Epsilon = GenerateDll("Epsilon", v2Directory, EpsilonSource, delta2Reference); EpsilonReferencingPublicSigned = GenerateDll("EpsilonReferencingPublicSigned", v2PublicSignedDirectory, EpsilonSource, MetadataReference.CreateFromFile(DeltaPublicSigned2.Path)); var v2BDirectory = _directory.CreateDirectory("Version2B"); Delta2B = GenerateDll("Delta", v2BDirectory, @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta.2B: "" + s); } } } "); var v3Directory = _directory.CreateDirectory("Version3"); Delta3 = GenerateDll("Delta", v3Directory, @" using System.Text; [assembly: System.Reflection.AssemblyTitle(""Delta"")] [assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] namespace Delta { public class D { public void Write(StringBuilder sb, string s) { sb.AppendLine(""Delta.3: "" + s); } } } "); var sciUserDirectory = _directory.CreateDirectory("SCIUser"); var compilerReference = MetadataReference.CreateFromFile(typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly.Location); UserSystemCollectionsImmutable = GenerateDll("System.Collections.Immutable", sciUserDirectory, @" namespace System.Collections.Immutable { public static class ImmutableArray { public static ImmutableArray<T> Create<T>(T t) => new(); } public struct ImmutableArray<T> { public int Length => 42; public static int MyMethod() => 42; } } ", compilerReference); var userSystemCollectionsImmutableReference = MetadataReference.CreateFromFile(UserSystemCollectionsImmutable.Path); AnalyzerReferencesSystemCollectionsImmutable1 = GenerateDll("AnalyzerUsesSystemCollectionsImmutable1", sciUserDirectory, @" using System.Text; using System.Collections.Immutable; public class Analyzer { public void Method(StringBuilder sb) { sb.Append(ImmutableArray<object>.MyMethod()); } } ", userSystemCollectionsImmutableReference, compilerReference); AnalyzerReferencesSystemCollectionsImmutable2 = GenerateDll("AnalyzerUsesSystemCollectionsImmutable2", sciUserDirectory, @" using System.Text; using System.Collections.Immutable; public class Analyzer { public void Method(StringBuilder sb) { sb.Append(ImmutableArray.Create(""a"").Length); } } ", userSystemCollectionsImmutableReference, compilerReference); var analyzerReferencesDelta1Directory = _directory.CreateDirectory("AnalyzerReferencesDelta1"); var delta1InAnalyzerReferencesDelta1 = analyzerReferencesDelta1Directory.CopyFile(Delta1.Path); AnalyzerReferencesDelta1 = GenerateDll("AnalyzerReferencesDelta1", _directory, @" using System.Text; using Delta; public class Analyzer { public void Method(StringBuilder sb) { var d = new D(); d.Write(sb, ""Hello""); } } ", MetadataReference.CreateFromFile(delta1InAnalyzerReferencesDelta1.Path), compilerReference); var faultyAnalyzerDirectory = _directory.CreateDirectory("FaultyAnalyzer"); FaultyAnalyzer = GenerateDll("FaultyAnalyzer", faultyAnalyzerDirectory, @" using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public abstract class TestAnalyzer : DiagnosticAnalyzer { } ", compilerReference); var realSciReference = MetadataReference.CreateFromFile(typeof(ImmutableArray).Assembly.Location); var analyzerWithDependencyDirectory = _directory.CreateDirectory("AnalyzerWithDependency"); AnalyzerDependency = GenerateDll("AnalyzerDependency", analyzerWithDependencyDirectory, @" using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; public abstract class AbstractTestAnalyzer : DiagnosticAnalyzer { protected static string SomeString = nameof(SomeString); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext context) { throw new NotImplementedException(); } } ", realSciReference, compilerReference); AnalyzerWithDependency = GenerateDll("Analyzer", analyzerWithDependencyDirectory, @" using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class TestAnalyzer : AbstractTestAnalyzer { private static string SomeString2 = AbstractTestAnalyzer.SomeString; }", realSciReference, compilerReference, MetadataReference.CreateFromFile(AnalyzerDependency.Path)); AnalyzerWithNativeDependency = GenerateDll("AnalyzerWithNativeDependency", _directory, @" using System; using System.Runtime.InteropServices; public class Class1 { [DllImport(""kernel32.dll"", CharSet = CharSet.Unicode, SetLastError = true)] private static extern int GetFileAttributesW(string lpFileName); public int GetFileAttributes(string path) { return GetFileAttributesW(path); } } "); } private static TempFile GenerateDll(string assemblyName, TempDirectory directory, string csSource, params MetadataReference[] additionalReferences) { return GenerateDll(assemblyName, directory, csSource, publicSign: false, additionalReferences); } private static TempFile GenerateDll(string assemblyName, TempDirectory directory, string csSource, bool publicSign, params MetadataReference[] additionalReferences) { CSharpCompilationOptions options = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: Diagnostic.MaxWarningLevel); if (publicSign) { options = options.WithPublicSign(true).WithCryptoPublicKey(SigningTestHelpers.PublicKey); } var analyzerDependencyCompilation = CSharpCompilation.Create( assemblyName: assemblyName, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(csSource) }, references: (new MetadataReference[] { NetStandard20.mscorlib, NetStandard20.netstandard, NetStandard20.SystemRuntime }).Concat(additionalReferences), options: options); var tempFile = directory.CreateFile($"{assemblyName}.dll"); tempFile.WriteAllBytes(analyzerDependencyCompilation.EmitToArray()); return tempFile; } public void Dispose() { _temp.Dispose(); } } }
1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Core/Test.Next/Remote/SnapshotSerializationTests.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.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Remote.UnitTests { [CollectionDefinition(Name)] public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture> { public const string Name = nameof(AssemblyLoadTestFixtureCollection); private AssemblyLoadTestFixtureCollection() { } } [Collection(AssemblyLoadTestFixtureCollection.Name)] [UseExportProvider] public class SnapshotSerializationTests { private readonly AssemblyLoadTestFixture _testFixture; public SnapshotSerializationTests(AssemblyLoadTestFixture testFixture) { _testFixture = testFixture; } private static Workspace CreateWorkspace(Type[] additionalParts = null) => new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).WithTestHostParts(TestHost.OutOfProcess).GetHostServices()); internal static Solution CreateFullSolution(Workspace workspace) { var solution = workspace.CurrentSolution; var languages = ImmutableHashSet.Create(LanguageNames.CSharp, LanguageNames.VisualBasic); var solutionOptions = solution.Workspace.Services.GetRequiredService<IOptionService>().GetSerializableOptionsSnapshot(languages); solution = solution.WithOptions(solutionOptions); var csCode = "class A { }"; var project1 = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document1 = project1.AddDocument("Document1", SourceText.From(csCode)); var vbCode = "Class B\r\nEnd Class"; var project2 = document1.Project.Solution.AddProject("Project2", "Project2.dll", LanguageNames.VisualBasic); var document2 = project2.AddDocument("Document2", SourceText.From(vbCode)); solution = document2.Project.Solution.GetRequiredProject(project1.Id) .AddProjectReference(new ProjectReference(project2.Id, ImmutableArray.Create("test"))) .AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddAnalyzerReference(new AnalyzerFileReference(Path.Combine(TempRoot.Root, "path1"), new TestAnalyzerAssemblyLoader())) .AddAdditionalDocument("Additional", SourceText.From("hello"), ImmutableArray.Create("test"), @".\Add").Project.Solution; return solution .WithAnalyzerReferences(new[] { new AnalyzerFileReference(Path.Combine(TempRoot.Root, "path2"), new TestAnalyzerAssemblyLoader()) }) .AddAnalyzerConfigDocuments( ImmutableArray.Create( DocumentInfo.Create( DocumentId.CreateNewId(project1.Id), ".editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("root = true"), VersionStamp.Create()))))); } [Fact] public async Task CreateSolutionSnapshotId_Empty() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); var checksum = scope.SolutionInfo.SolutionChecksum; var solutionSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, checksum, CancellationToken.None).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(solutionSyncObject).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false); var projectsSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, solutionObject.Projects.Checksum, CancellationToken.None).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(projectsSyncObject).ConfigureAwait(false); Assert.Equal(0, solutionObject.Projects.Count); } [Fact] public async Task CreateSolutionSnapshotId_Empty_Serialization() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); await validator.VerifySolutionStateSerializationAsync(solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Project() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); var checksum = scope.SolutionInfo.SolutionChecksum; var solutionSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, checksum, CancellationToken.None).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(solutionSyncObject).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes); await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet); var projectSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, solutionObject.Projects.Checksum, CancellationToken.None).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(projectSyncObject).ConfigureAwait(false); Assert.Equal(1, solutionObject.Projects.Count); await validator.VerifySnapshotInServiceAsync(validator.ToProjectObjects(solutionObject.Projects)[0], 0, 0, 0, 0, 0).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Project_Serialization() { using var workspace = CreateWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var validator = new SerializationValidator(workspace.Services); using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); await validator.VerifySolutionStateSerializationAsync(project.Solution, snapshot.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId() { var code = "class A { }"; using var workspace = CreateWorkspace(); var document = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code)); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(document.Project.Solution, CancellationToken.None).ConfigureAwait(false); var syncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(syncObject.Checksum).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(syncObject).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Projects.Checksum, WellKnownSynchronizationKind.ChecksumCollection).ConfigureAwait(false); Assert.Equal(1, solutionObject.Projects.Count); await validator.VerifySnapshotInServiceAsync(validator.ToProjectObjects(solutionObject.Projects)[0], 1, 0, 0, 0, 0).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Serialization() { var code = "class A { }"; using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var document = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code)); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(document.Project.Solution, CancellationToken.None).ConfigureAwait(false); await validator.VerifySolutionStateSerializationAsync(document.Project.Solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Full() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var firstProjectChecksum = await solution.GetProject(solution.ProjectIds[0]).State.GetChecksumAsync(CancellationToken.None); var secondProjectChecksum = await solution.GetProject(solution.ProjectIds[1]).State.GetChecksumAsync(CancellationToken.None); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); var syncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(syncObject.Checksum).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(syncObject).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Projects.Checksum, WellKnownSynchronizationKind.ChecksumCollection).ConfigureAwait(false); Assert.Equal(2, solutionObject.Projects.Count); var projects = validator.ToProjectObjects(solutionObject.Projects); await validator.VerifySnapshotInServiceAsync(projects.Where(p => p.Checksum == firstProjectChecksum).First(), 1, 1, 1, 1, 1).ConfigureAwait(false); await validator.VerifySnapshotInServiceAsync(projects.Where(p => p.Checksum == secondProjectChecksum).First(), 1, 0, 0, 0, 0).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Full_Serialization() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); await validator.VerifySolutionStateSerializationAsync(solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Full_Asset_Serialization() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(scope.SolutionInfo.SolutionChecksum); await validator.VerifyAssetAsync(solutionObject).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Full_Asset_Serialization_Desktop() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(scope.SolutionInfo.SolutionChecksum); await validator.VerifyAssetAsync(solutionObject).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Duplicate() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); // this is just data, one can hold the id outside of using statement. but // one can't get asset using checksum from the id. SolutionStateChecksums solutionId1; SolutionStateChecksums solutionId2; var validator = new SerializationValidator(workspace.Services); using (var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false)) { solutionId1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } using (var scope2 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false)) { solutionId2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } // once pinned snapshot scope is released, there is no way to get back to asset. // catch Exception because it will throw 2 different exception based on release or debug (ExceptionUtilities.UnexpectedValue) Assert.ThrowsAny<Exception>(() => validator.SolutionStateEqual(solutionId1, solutionId2)); } [Fact] public void MetadataReference_RoundTrip_Test() { using var workspace = CreateWorkspace(); var reference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); var serializer = workspace.Services.GetService<ISerializerService>(); var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public async Task Workspace_RoundTrip_Test() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var validator = new SerializationValidator(workspace.Services); var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); // recover solution from given snapshot var recovered = await validator.GetSolutionAsync(scope1).ConfigureAwait(false); var solutionObject1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false); // create new snapshot from recovered solution using var scope2 = await validator.AssetStorage.StoreAssetsAsync(recovered, CancellationToken.None).ConfigureAwait(false); // verify asset created by recovered solution is good var solutionObject2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false); await validator.VerifyAssetAsync(solutionObject2).ConfigureAwait(false); // verify snapshots created from original solution and recovered solution are same validator.SolutionStateEqual(solutionObject1, solutionObject2); // recover new solution from recovered solution var roundtrip = await validator.GetSolutionAsync(scope2).ConfigureAwait(false); // create new snapshot from round tripped solution using var scope3 = await validator.AssetStorage.StoreAssetsAsync(roundtrip, CancellationToken.None).ConfigureAwait(false); // verify asset created by rount trip solution is good var solutionObject3 = await validator.GetValueAsync<SolutionStateChecksums>(scope3.SolutionInfo.SolutionChecksum).ConfigureAwait(false); await validator.VerifyAssetAsync(solutionObject3).ConfigureAwait(false); // verify snapshots created from original solution and round trip solution are same. validator.SolutionStateEqual(solutionObject2, solutionObject3); } [Fact] public async Task Workspace_RoundTrip_Test_Desktop() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var validator = new SerializationValidator(workspace.Services); var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); // recover solution from given snapshot var recovered = await validator.GetSolutionAsync(scope1).ConfigureAwait(false); var solutionObject1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false); // create new snapshot from recovered solution using var scope2 = await validator.AssetStorage.StoreAssetsAsync(recovered, CancellationToken.None).ConfigureAwait(false); // verify asset created by recovered solution is good var solutionObject2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false); await validator.VerifyAssetAsync(solutionObject2).ConfigureAwait(false); // verify snapshots created from original solution and recovered solution are same validator.SolutionStateEqual(solutionObject1, solutionObject2); scope1.Dispose(); // recover new solution from recovered solution var roundtrip = await validator.GetSolutionAsync(scope2).ConfigureAwait(false); // create new snapshot from round tripped solution using var scope3 = await validator.AssetStorage.StoreAssetsAsync(roundtrip, CancellationToken.None).ConfigureAwait(false); // verify asset created by rount trip solution is good var solutionObject3 = await validator.GetValueAsync<SolutionStateChecksums>(scope3.SolutionInfo.SolutionChecksum).ConfigureAwait(false); await validator.VerifyAssetAsync(solutionObject3).ConfigureAwait(false); // verify snapshots created from original solution and round trip solution are same. validator.SolutionStateEqual(solutionObject2, solutionObject3); } [Fact] public async Task OptionSet_Serialization() { using var workspace = CreateWorkspace() .CurrentSolution.AddProject("Project1", "Project.dll", LanguageNames.CSharp) .Solution.AddProject("Project2", "Project2.dll", LanguageNames.VisualBasic) .Solution.Workspace; await VerifyOptionSetsAsync(workspace, _ => { }).ConfigureAwait(false); } [Fact] public async Task OptionSet_Serialization_CustomValue() { using var workspace = CreateWorkspace(); var newQualifyFieldAccessValue = new CodeStyleOption2<bool>(false, NotificationOption2.Error); var newQualifyMethodAccessValue = new CodeStyleOption2<bool>(true, NotificationOption2.Warning); var newVarWhenTypeIsApparentValue = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); var newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp, newQualifyFieldAccessValue) .WithChangedOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.VisualBasic, newQualifyMethodAccessValue) .WithChangedOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, newVarWhenTypeIsApparentValue) .WithChangedOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic, newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue))); var validator = new SerializationValidator(workspace.Services); await VerifyOptionSetsAsync(workspace, VerifyOptions).ConfigureAwait(false); void VerifyOptions(OptionSet options) { var actualQualifyFieldAccessValue = options.GetOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp); Assert.Equal(newQualifyFieldAccessValue, actualQualifyFieldAccessValue); var actualQualifyMethodAccessValue = options.GetOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.VisualBasic); Assert.Equal(newQualifyMethodAccessValue, actualQualifyMethodAccessValue); var actualVarWhenTypeIsApparentValue = options.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent); Assert.Equal(newVarWhenTypeIsApparentValue, actualVarWhenTypeIsApparentValue); var actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = options.GetOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic); Assert.Equal(newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue, actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue); } } [Fact] public void Missing_Metadata_Serialization_Test() { using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); var reference = new MissingMetadataReference(); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public void Missing_Analyzer_Serialization_Test() { using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); var reference = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader()); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public void Missing_Analyzer_Serialization_Desktop_Test() { using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); var reference = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader()); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public void RoundTrip_Analyzer_Serialization_Test() { using var tempRoot = new TempRoot(); using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); // actually shadow copy content var location = typeof(object).Assembly.Location; var file = tempRoot.CreateFile("shadow", "dll"); file.CopyContentFrom(location); var reference = new AnalyzerFileReference(location, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(location, file.Path))); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public void RoundTrip_Analyzer_Serialization_Desktop_Test() { using var tempRoot = new TempRoot(); using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); // actually shadow copy content var location = typeof(object).Assembly.Location; var file = tempRoot.CreateFile("shadow", "dll"); file.CopyContentFrom(location); var reference = new AnalyzerFileReference(location, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(location, file.Path))); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public void ShadowCopied_Analyzer_Serialization_Desktop_Test() { using var tempRoot = new TempRoot(); using var workspace = CreateWorkspace(); var reference = CreateShadowCopiedAnalyzerReference(tempRoot); var serializer = workspace.Services.GetService<ISerializerService>(); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); // this will verify serialized analyzer reference return same checksum as the original one _ = CloneAsset(serializer, assetFromFile); } [Fact] [WorkItem(1107294, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1107294")] public async Task SnapshotWithIdenticalAnalyzerFiles() { using var workspace = CreateWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); using var temp = new TempRoot(); var dir = temp.CreateDirectory(); // create two analyzer assembly files whose content is identical but path is different: var file1 = dir.CreateFile("analyzer1.dll").CopyContentFrom(_testFixture.FaultyAnalyzer.Path); var file2 = dir.CreateFile("analyzer2.dll").CopyContentFrom(_testFixture.FaultyAnalyzer.Path); var analyzer1 = new AnalyzerFileReference(file1.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented); var analyzer2 = new AnalyzerFileReference(file2.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented); project = project.AddAnalyzerReferences(new[] { analyzer1, analyzer2 }); var validator = new SerializationValidator(workspace.Services); using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false); AssertEx.Equal(new[] { file1.Path, file2.Path }, recovered.GetProject(project.Id).AnalyzerReferences.Select(r => r.FullPath)); } [Fact] public async Task SnapshotWithMissingReferencesTest() { using var workspace = CreateWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var metadata = new MissingMetadataReference(); var analyzer = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader()); project = project.AddMetadataReference(metadata); project = project.AddAnalyzerReference(analyzer); var validator = new SerializationValidator(workspace.Services); using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); // this shouldn't throw var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false); } [Fact] public async Task UnknownLanguageTest() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", NoCompilationConstants.LanguageName); var validator = new SerializationValidator(workspace.Services); using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); // this shouldn't throw var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false); } [Fact, WorkItem(44791, "https://github.com/dotnet/roslyn/issues/44791")] public async Task UnknownLanguageOptionsTest() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", NoCompilationConstants.LanguageName) .Solution.AddProject("Project2", "Project2.dll", LanguageNames.CSharp); workspace.TryApplyChanges(project.Solution); await VerifyOptionSetsAsync(workspace, verifyOptionValues: _ => { }); } [Fact] public async Task EmptyAssetChecksumTest() { var document = CreateWorkspace().CurrentSolution.AddProject("empty", "empty", LanguageNames.CSharp).AddDocument("empty", SourceText.From("")); var serializer = document.Project.Solution.Workspace.Services.GetService<ISerializerService>(); var source = serializer.CreateChecksum(await document.GetTextAsync().ConfigureAwait(false), CancellationToken.None); var metadata = serializer.CreateChecksum(new MissingMetadataReference(), CancellationToken.None); var analyzer = serializer.CreateChecksum(new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing"), new MissingAnalyzerLoader()), CancellationToken.None); Assert.NotEqual(source, metadata); Assert.NotEqual(source, analyzer); Assert.NotEqual(metadata, analyzer); } [Fact] public async Task VBParseOptionsInCompilationOptions() { var project = CreateWorkspace().CurrentSolution.AddProject("empty", "empty", LanguageNames.VisualBasic); project = project.WithCompilationOptions( ((VisualBasic.VisualBasicCompilationOptions)project.CompilationOptions).WithParseOptions((VisualBasic.VisualBasicParseOptions)project.ParseOptions)); var checksum = await project.State.GetChecksumAsync(CancellationToken.None).ConfigureAwait(false); Assert.NotNull(checksum); } [Fact] public async Task TestMetadataXmlDocComment() { using var tempRoot = new TempRoot(); // get original assembly location var mscorlibLocation = typeof(object).Assembly.Location; // set up dll and xml doc content var tempDir = tempRoot.CreateDirectory(); var tempCorlib = tempDir.CopyFile(mscorlibLocation); var tempCorlibXml = tempDir.CreateFile(Path.ChangeExtension(tempCorlib.Path, "xml")); tempCorlibXml.WriteAllText(@"<?xml version=""1.0"" encoding=""utf-8""?> <doc> <assembly> <name>mscorlib</name> </assembly> <members> <member name=""T:System.Object""> <summary>Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.To browse the .NET Framework source code for this type, see the Reference Source.</summary> </member> </members> </doc>"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject("Project", "Project.dll", LanguageNames.CSharp) .AddMetadataReference(MetadataReference.CreateFromFile(tempCorlib.Path)) .Solution; var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None); // recover solution from given snapshot var recovered = await validator.GetSolutionAsync(scope); var compilation = await recovered.Projects.First().GetCompilationAsync(CancellationToken.None); var objectType = compilation.GetTypeByMetadataName("System.Object"); var xmlDocComment = objectType.GetDocumentationCommentXml(); Assert.False(string.IsNullOrEmpty(xmlDocComment)); } [Fact] public void TestEncodingSerialization() { using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); // test with right serializable encoding var sourceText = SourceText.From("Hello", Encoding.UTF8); using (var stream = SerializableBytes.CreateWritableStream()) { using var context = SolutionReplicationContext.Create(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { serializer.Serialize(sourceText, objectWriter, context, CancellationToken.None); } stream.Position = 0; using var objectReader = ObjectReader.TryGetReader(stream); var newText = serializer.Deserialize<SourceText>(sourceText.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None); Assert.Equal(sourceText.ToString(), newText.ToString()); } // test with wrong encoding that doesn't support serialization sourceText = SourceText.From("Hello", new NotSerializableEncoding()); using (var stream = SerializableBytes.CreateWritableStream()) { using var context = SolutionReplicationContext.Create(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { serializer.Serialize(sourceText, objectWriter, context, CancellationToken.None); } stream.Position = 0; using var objectReader = ObjectReader.TryGetReader(stream); var newText = serializer.Deserialize<SourceText>(sourceText.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None); Assert.Equal(sourceText.ToString(), newText.ToString()); } } [Fact] public void TestCompilationOptions_NullableAndImport() { var csharpOptions = CSharp.CSharpCompilation.Create("dummy").Options.WithNullableContextOptions(NullableContextOptions.Warnings).WithMetadataImportOptions(MetadataImportOptions.All); var vbOptions = VisualBasic.VisualBasicCompilation.Create("dummy").Options.WithMetadataImportOptions(MetadataImportOptions.Internal); using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); VerifyOptions(csharpOptions); VerifyOptions(vbOptions); void VerifyOptions(CompilationOptions originalOptions) { using var stream = SerializableBytes.CreateWritableStream(); using var context = SolutionReplicationContext.Create(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { serializer.Serialize(originalOptions, objectWriter, context, CancellationToken.None); } stream.Position = 0; using var objectReader = ObjectReader.TryGetReader(stream); var recoveredOptions = serializer.Deserialize<CompilationOptions>(originalOptions.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None); var original = serializer.CreateChecksum(originalOptions, CancellationToken.None); var recovered = serializer.CreateChecksum(recoveredOptions, CancellationToken.None); Assert.Equal(original, recovered); } } private static async Task VerifyOptionSetsAsync(Workspace workspace, Action<OptionSet> verifyOptionValues) { var solution = workspace.CurrentSolution; verifyOptionValues(workspace.Options); verifyOptionValues(solution.Options); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); var checksum = scope.SolutionInfo.SolutionChecksum; var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes); await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet); var recoveredSolution = await validator.GetSolutionAsync(scope); // option should be exactly same Assert.Equal(0, recoveredSolution.Options.GetChangedOptions(workspace.Options).Count()); verifyOptionValues(workspace.Options); verifyOptionValues(recoveredSolution.Options); // checksum for recovered solution should be the same. using var recoveredScope = await validator.AssetStorage.StoreAssetsAsync(recoveredSolution, CancellationToken.None).ConfigureAwait(false); var recoveredChecksum = recoveredScope.SolutionInfo.SolutionChecksum; Assert.Equal(checksum, recoveredChecksum); } private static SolutionAsset CloneAsset(ISerializerService serializer, SolutionAsset asset) { using var stream = SerializableBytes.CreateWritableStream(); using var context = SolutionReplicationContext.Create(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { serializer.Serialize(asset.Value, writer, context, CancellationToken.None); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); var recovered = serializer.Deserialize<object>(asset.Kind, reader, CancellationToken.None); var assetFromStorage = new SolutionAsset(serializer.CreateChecksum(recovered, CancellationToken.None), recovered); Assert.Equal(asset.Checksum, assetFromStorage.Checksum); return assetFromStorage; } private static AnalyzerFileReference CreateShadowCopiedAnalyzerReference(TempRoot tempRoot) { // use 2 different files as shadow copied content var original = typeof(AdhocWorkspace).Assembly.Location; var shadow = tempRoot.CreateFile("shadow", "dll"); shadow.CopyContentFrom(typeof(object).Assembly.Location); return new AnalyzerFileReference(original, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(original, shadow.Path))); } private class MissingAnalyzerLoader : AnalyzerAssemblyLoader { protected override Assembly LoadFromPathImpl(string fullPath) => throw new FileNotFoundException(fullPath); } private class MissingMetadataReference : PortableExecutableReference { public MissingMetadataReference() : base(MetadataReferenceProperties.Assembly, "missing_reference", XmlDocumentationProvider.Default) { } protected override DocumentationProvider CreateDocumentationProvider() => null; protected override Metadata GetMetadataImpl() => throw new FileNotFoundException("can't find"); protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) => this; } private class MockShadowCopyAnalyzerAssemblyLoader : IAnalyzerAssemblyLoader { private readonly ImmutableDictionary<string, string> _map; public MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string> map) => _map = map; public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) => Assembly.LoadFrom(_map[fullPath]); } private class NotSerializableEncoding : Encoding { private readonly Encoding _real = Encoding.UTF8; public override string WebName => _real.WebName; public override int GetByteCount(char[] chars, int index, int count) => _real.GetByteCount(chars, index, count); public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) => GetBytes(chars, charIndex, charCount, bytes, byteIndex); public override int GetCharCount(byte[] bytes, int index, int count) => GetCharCount(bytes, index, count); public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) => GetChars(bytes, byteIndex, byteCount, chars, charIndex); public override int GetMaxByteCount(int charCount) => GetMaxByteCount(charCount); public override int GetMaxCharCount(int byteCount) => GetMaxCharCount(byteCount); } } }
// 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.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Remote.UnitTests { [CollectionDefinition(Name)] public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture> { public const string Name = nameof(AssemblyLoadTestFixtureCollection); private AssemblyLoadTestFixtureCollection() { } } [Collection(AssemblyLoadTestFixtureCollection.Name)] [UseExportProvider] public class SnapshotSerializationTests { private readonly AssemblyLoadTestFixture _testFixture; public SnapshotSerializationTests(AssemblyLoadTestFixture testFixture) { _testFixture = testFixture; } private static Workspace CreateWorkspace(Type[] additionalParts = null) => new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).WithTestHostParts(TestHost.OutOfProcess).GetHostServices()); internal static Solution CreateFullSolution(Workspace workspace) { var solution = workspace.CurrentSolution; var languages = ImmutableHashSet.Create(LanguageNames.CSharp, LanguageNames.VisualBasic); var solutionOptions = solution.Workspace.Services.GetRequiredService<IOptionService>().GetSerializableOptionsSnapshot(languages); solution = solution.WithOptions(solutionOptions); var csCode = "class A { }"; var project1 = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document1 = project1.AddDocument("Document1", SourceText.From(csCode)); var vbCode = "Class B\r\nEnd Class"; var project2 = document1.Project.Solution.AddProject("Project2", "Project2.dll", LanguageNames.VisualBasic); var document2 = project2.AddDocument("Document2", SourceText.From(vbCode)); solution = document2.Project.Solution.GetRequiredProject(project1.Id) .AddProjectReference(new ProjectReference(project2.Id, ImmutableArray.Create("test"))) .AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddAnalyzerReference(new AnalyzerFileReference(Path.Combine(TempRoot.Root, "path1"), new TestAnalyzerAssemblyLoader())) .AddAdditionalDocument("Additional", SourceText.From("hello"), ImmutableArray.Create("test"), @".\Add").Project.Solution; return solution .WithAnalyzerReferences(new[] { new AnalyzerFileReference(Path.Combine(TempRoot.Root, "path2"), new TestAnalyzerAssemblyLoader()) }) .AddAnalyzerConfigDocuments( ImmutableArray.Create( DocumentInfo.Create( DocumentId.CreateNewId(project1.Id), ".editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("root = true"), VersionStamp.Create()))))); } [Fact] public async Task CreateSolutionSnapshotId_Empty() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); var checksum = scope.SolutionInfo.SolutionChecksum; var solutionSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, checksum, CancellationToken.None).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(solutionSyncObject).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false); var projectsSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, solutionObject.Projects.Checksum, CancellationToken.None).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(projectsSyncObject).ConfigureAwait(false); Assert.Equal(0, solutionObject.Projects.Count); } [Fact] public async Task CreateSolutionSnapshotId_Empty_Serialization() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); await validator.VerifySolutionStateSerializationAsync(solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Project() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); var checksum = scope.SolutionInfo.SolutionChecksum; var solutionSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, checksum, CancellationToken.None).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(solutionSyncObject).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes); await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet); var projectSyncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, solutionObject.Projects.Checksum, CancellationToken.None).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(projectSyncObject).ConfigureAwait(false); Assert.Equal(1, solutionObject.Projects.Count); await validator.VerifySnapshotInServiceAsync(validator.ToProjectObjects(solutionObject.Projects)[0], 0, 0, 0, 0, 0).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Project_Serialization() { using var workspace = CreateWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var validator = new SerializationValidator(workspace.Services); using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); await validator.VerifySolutionStateSerializationAsync(project.Solution, snapshot.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId() { var code = "class A { }"; using var workspace = CreateWorkspace(); var document = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code)); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(document.Project.Solution, CancellationToken.None).ConfigureAwait(false); var syncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(syncObject.Checksum).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(syncObject).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Projects.Checksum, WellKnownSynchronizationKind.ChecksumCollection).ConfigureAwait(false); Assert.Equal(1, solutionObject.Projects.Count); await validator.VerifySnapshotInServiceAsync(validator.ToProjectObjects(solutionObject.Projects)[0], 1, 0, 0, 0, 0).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Serialization() { var code = "class A { }"; using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var document = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp).AddDocument("Document", SourceText.From(code)); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(document.Project.Solution, CancellationToken.None).ConfigureAwait(false); await validator.VerifySolutionStateSerializationAsync(document.Project.Solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Full() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var firstProjectChecksum = await solution.GetProject(solution.ProjectIds[0]).State.GetChecksumAsync(CancellationToken.None); var secondProjectChecksum = await solution.GetProject(solution.ProjectIds[1]).State.GetChecksumAsync(CancellationToken.None); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); var syncObject = await validator.AssetStorage.GetAssetAsync(scope.SolutionInfo.ScopeId, scope.SolutionInfo.SolutionChecksum, CancellationToken.None).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(syncObject.Checksum).ConfigureAwait(false); await validator.VerifySynchronizationObjectInServiceAsync(syncObject).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Projects.Checksum, WellKnownSynchronizationKind.ChecksumCollection).ConfigureAwait(false); Assert.Equal(2, solutionObject.Projects.Count); var projects = validator.ToProjectObjects(solutionObject.Projects); await validator.VerifySnapshotInServiceAsync(projects.Where(p => p.Checksum == firstProjectChecksum).First(), 1, 1, 1, 1, 1).ConfigureAwait(false); await validator.VerifySnapshotInServiceAsync(projects.Where(p => p.Checksum == secondProjectChecksum).First(), 1, 0, 0, 0, 0).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Full_Serialization() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); await validator.VerifySolutionStateSerializationAsync(solution, scope.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Full_Asset_Serialization() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(scope.SolutionInfo.SolutionChecksum); await validator.VerifyAssetAsync(solutionObject).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Full_Asset_Serialization_Desktop() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(scope.SolutionInfo.SolutionChecksum); await validator.VerifyAssetAsync(solutionObject).ConfigureAwait(false); } [Fact] public async Task CreateSolutionSnapshotId_Duplicate() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); // this is just data, one can hold the id outside of using statement. but // one can't get asset using checksum from the id. SolutionStateChecksums solutionId1; SolutionStateChecksums solutionId2; var validator = new SerializationValidator(workspace.Services); using (var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false)) { solutionId1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } using (var scope2 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false)) { solutionId2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false); } // once pinned snapshot scope is released, there is no way to get back to asset. // catch Exception because it will throw 2 different exception based on release or debug (ExceptionUtilities.UnexpectedValue) Assert.ThrowsAny<Exception>(() => validator.SolutionStateEqual(solutionId1, solutionId2)); } [Fact] public void MetadataReference_RoundTrip_Test() { using var workspace = CreateWorkspace(); var reference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); var serializer = workspace.Services.GetService<ISerializerService>(); var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public async Task Workspace_RoundTrip_Test() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var validator = new SerializationValidator(workspace.Services); var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); // recover solution from given snapshot var recovered = await validator.GetSolutionAsync(scope1).ConfigureAwait(false); var solutionObject1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false); // create new snapshot from recovered solution using var scope2 = await validator.AssetStorage.StoreAssetsAsync(recovered, CancellationToken.None).ConfigureAwait(false); // verify asset created by recovered solution is good var solutionObject2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false); await validator.VerifyAssetAsync(solutionObject2).ConfigureAwait(false); // verify snapshots created from original solution and recovered solution are same validator.SolutionStateEqual(solutionObject1, solutionObject2); // recover new solution from recovered solution var roundtrip = await validator.GetSolutionAsync(scope2).ConfigureAwait(false); // create new snapshot from round tripped solution using var scope3 = await validator.AssetStorage.StoreAssetsAsync(roundtrip, CancellationToken.None).ConfigureAwait(false); // verify asset created by rount trip solution is good var solutionObject3 = await validator.GetValueAsync<SolutionStateChecksums>(scope3.SolutionInfo.SolutionChecksum).ConfigureAwait(false); await validator.VerifyAssetAsync(solutionObject3).ConfigureAwait(false); // verify snapshots created from original solution and round trip solution are same. validator.SolutionStateEqual(solutionObject2, solutionObject3); } [Fact] public async Task Workspace_RoundTrip_Test_Desktop() { using var workspace = CreateWorkspace(); var solution = CreateFullSolution(workspace); var validator = new SerializationValidator(workspace.Services); var scope1 = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); // recover solution from given snapshot var recovered = await validator.GetSolutionAsync(scope1).ConfigureAwait(false); var solutionObject1 = await validator.GetValueAsync<SolutionStateChecksums>(scope1.SolutionInfo.SolutionChecksum).ConfigureAwait(false); // create new snapshot from recovered solution using var scope2 = await validator.AssetStorage.StoreAssetsAsync(recovered, CancellationToken.None).ConfigureAwait(false); // verify asset created by recovered solution is good var solutionObject2 = await validator.GetValueAsync<SolutionStateChecksums>(scope2.SolutionInfo.SolutionChecksum).ConfigureAwait(false); await validator.VerifyAssetAsync(solutionObject2).ConfigureAwait(false); // verify snapshots created from original solution and recovered solution are same validator.SolutionStateEqual(solutionObject1, solutionObject2); scope1.Dispose(); // recover new solution from recovered solution var roundtrip = await validator.GetSolutionAsync(scope2).ConfigureAwait(false); // create new snapshot from round tripped solution using var scope3 = await validator.AssetStorage.StoreAssetsAsync(roundtrip, CancellationToken.None).ConfigureAwait(false); // verify asset created by rount trip solution is good var solutionObject3 = await validator.GetValueAsync<SolutionStateChecksums>(scope3.SolutionInfo.SolutionChecksum).ConfigureAwait(false); await validator.VerifyAssetAsync(solutionObject3).ConfigureAwait(false); // verify snapshots created from original solution and round trip solution are same. validator.SolutionStateEqual(solutionObject2, solutionObject3); } [Fact] public async Task OptionSet_Serialization() { using var workspace = CreateWorkspace() .CurrentSolution.AddProject("Project1", "Project.dll", LanguageNames.CSharp) .Solution.AddProject("Project2", "Project2.dll", LanguageNames.VisualBasic) .Solution.Workspace; await VerifyOptionSetsAsync(workspace, _ => { }).ConfigureAwait(false); } [Fact] public async Task OptionSet_Serialization_CustomValue() { using var workspace = CreateWorkspace(); var newQualifyFieldAccessValue = new CodeStyleOption2<bool>(false, NotificationOption2.Error); var newQualifyMethodAccessValue = new CodeStyleOption2<bool>(true, NotificationOption2.Warning); var newVarWhenTypeIsApparentValue = new CodeStyleOption2<bool>(false, NotificationOption2.Suggestion); var newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp, newQualifyFieldAccessValue) .WithChangedOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.VisualBasic, newQualifyMethodAccessValue) .WithChangedOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent, newVarWhenTypeIsApparentValue) .WithChangedOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic, newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue))); var validator = new SerializationValidator(workspace.Services); await VerifyOptionSetsAsync(workspace, VerifyOptions).ConfigureAwait(false); void VerifyOptions(OptionSet options) { var actualQualifyFieldAccessValue = options.GetOption(CodeStyleOptions2.QualifyFieldAccess, LanguageNames.CSharp); Assert.Equal(newQualifyFieldAccessValue, actualQualifyFieldAccessValue); var actualQualifyMethodAccessValue = options.GetOption(CodeStyleOptions2.QualifyMethodAccess, LanguageNames.VisualBasic); Assert.Equal(newQualifyMethodAccessValue, actualQualifyMethodAccessValue); var actualVarWhenTypeIsApparentValue = options.GetOption(CSharpCodeStyleOptions.VarWhenTypeIsApparent); Assert.Equal(newVarWhenTypeIsApparentValue, actualVarWhenTypeIsApparentValue); var actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue = options.GetOption(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic); Assert.Equal(newPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue, actualPreferIntrinsicPredefinedTypeKeywordInMemberAccessValue); } } [Fact] public void Missing_Metadata_Serialization_Test() { using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); var reference = new MissingMetadataReference(); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public void Missing_Analyzer_Serialization_Test() { using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); var reference = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader()); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public void Missing_Analyzer_Serialization_Desktop_Test() { using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); var reference = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader()); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public void RoundTrip_Analyzer_Serialization_Test() { using var tempRoot = new TempRoot(); using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); // actually shadow copy content var location = typeof(object).Assembly.Location; var file = tempRoot.CreateFile("shadow", "dll"); file.CopyContentFrom(location); var reference = new AnalyzerFileReference(location, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(location, file.Path))); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public void RoundTrip_Analyzer_Serialization_Desktop_Test() { using var tempRoot = new TempRoot(); using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); // actually shadow copy content var location = typeof(object).Assembly.Location; var file = tempRoot.CreateFile("shadow", "dll"); file.CopyContentFrom(location); var reference = new AnalyzerFileReference(location, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(location, file.Path))); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); var assetFromStorage = CloneAsset(serializer, assetFromFile); _ = CloneAsset(serializer, assetFromStorage); } [Fact] public void ShadowCopied_Analyzer_Serialization_Desktop_Test() { using var tempRoot = new TempRoot(); using var workspace = CreateWorkspace(); var reference = CreateShadowCopiedAnalyzerReference(tempRoot); var serializer = workspace.Services.GetService<ISerializerService>(); // make sure this doesn't throw var assetFromFile = new SolutionAsset(serializer.CreateChecksum(reference, CancellationToken.None), reference); // this will verify serialized analyzer reference return same checksum as the original one _ = CloneAsset(serializer, assetFromFile); } [Fact] [WorkItem(1107294, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1107294")] public async Task SnapshotWithIdenticalAnalyzerFiles() { using var workspace = CreateWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); using var temp = new TempRoot(); var dir = temp.CreateDirectory(); // create two analyzer assembly files whose content is identical but path is different: var file1 = dir.CreateFile("analyzer1.dll").CopyContentFrom(_testFixture.FaultyAnalyzer.Path); var file2 = dir.CreateFile("analyzer2.dll").CopyContentFrom(_testFixture.FaultyAnalyzer.Path); var analyzer1 = new AnalyzerFileReference(file1.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented); var analyzer2 = new AnalyzerFileReference(file2.Path, TestAnalyzerAssemblyLoader.LoadNotImplemented); project = project.AddAnalyzerReferences(new[] { analyzer1, analyzer2 }); var validator = new SerializationValidator(workspace.Services); using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false); AssertEx.Equal(new[] { file1.Path, file2.Path }, recovered.GetProject(project.Id).AnalyzerReferences.Select(r => r.FullPath)); } [Fact] public async Task SnapshotWithMissingReferencesTest() { using var workspace = CreateWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var metadata = new MissingMetadataReference(); var analyzer = new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing_reference"), new MissingAnalyzerLoader()); project = project.AddMetadataReference(metadata); project = project.AddAnalyzerReference(analyzer); var validator = new SerializationValidator(workspace.Services); using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); // this shouldn't throw var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false); } [Fact] public async Task UnknownLanguageTest() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", NoCompilationConstants.LanguageName); var validator = new SerializationValidator(workspace.Services); using var snapshot = await validator.AssetStorage.StoreAssetsAsync(project.Solution, CancellationToken.None).ConfigureAwait(false); // this shouldn't throw var recovered = await validator.GetSolutionAsync(snapshot).ConfigureAwait(false); } [Fact, WorkItem(44791, "https://github.com/dotnet/roslyn/issues/44791")] public async Task UnknownLanguageOptionsTest() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", NoCompilationConstants.LanguageName) .Solution.AddProject("Project2", "Project2.dll", LanguageNames.CSharp); workspace.TryApplyChanges(project.Solution); await VerifyOptionSetsAsync(workspace, verifyOptionValues: _ => { }); } [Fact] public async Task EmptyAssetChecksumTest() { var document = CreateWorkspace().CurrentSolution.AddProject("empty", "empty", LanguageNames.CSharp).AddDocument("empty", SourceText.From("")); var serializer = document.Project.Solution.Workspace.Services.GetService<ISerializerService>(); var source = serializer.CreateChecksum(await document.GetTextAsync().ConfigureAwait(false), CancellationToken.None); var metadata = serializer.CreateChecksum(new MissingMetadataReference(), CancellationToken.None); var analyzer = serializer.CreateChecksum(new AnalyzerFileReference(Path.Combine(TempRoot.Root, "missing"), new MissingAnalyzerLoader()), CancellationToken.None); Assert.NotEqual(source, metadata); Assert.NotEqual(source, analyzer); Assert.NotEqual(metadata, analyzer); } [Fact] public async Task VBParseOptionsInCompilationOptions() { var project = CreateWorkspace().CurrentSolution.AddProject("empty", "empty", LanguageNames.VisualBasic); project = project.WithCompilationOptions( ((VisualBasic.VisualBasicCompilationOptions)project.CompilationOptions).WithParseOptions((VisualBasic.VisualBasicParseOptions)project.ParseOptions)); var checksum = await project.State.GetChecksumAsync(CancellationToken.None).ConfigureAwait(false); Assert.NotNull(checksum); } [Fact] public async Task TestMetadataXmlDocComment() { using var tempRoot = new TempRoot(); // get original assembly location var mscorlibLocation = typeof(object).Assembly.Location; // set up dll and xml doc content var tempDir = tempRoot.CreateDirectory(); var tempCorlib = tempDir.CopyFile(mscorlibLocation); var tempCorlibXml = tempDir.CreateFile(Path.ChangeExtension(tempCorlib.Path, "xml")); tempCorlibXml.WriteAllText(@"<?xml version=""1.0"" encoding=""utf-8""?> <doc> <assembly> <name>mscorlib</name> </assembly> <members> <member name=""T:System.Object""> <summary>Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.To browse the .NET Framework source code for this type, see the Reference Source.</summary> </member> </members> </doc>"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject("Project", "Project.dll", LanguageNames.CSharp) .AddMetadataReference(MetadataReference.CreateFromFile(tempCorlib.Path)) .Solution; var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None); // recover solution from given snapshot var recovered = await validator.GetSolutionAsync(scope); var compilation = await recovered.Projects.First().GetCompilationAsync(CancellationToken.None); var objectType = compilation.GetTypeByMetadataName("System.Object"); var xmlDocComment = objectType.GetDocumentationCommentXml(); Assert.False(string.IsNullOrEmpty(xmlDocComment)); } [Fact] public void TestEncodingSerialization() { using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); // test with right serializable encoding var sourceText = SourceText.From("Hello", Encoding.UTF8); using (var stream = SerializableBytes.CreateWritableStream()) { using var context = SolutionReplicationContext.Create(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { serializer.Serialize(sourceText, objectWriter, context, CancellationToken.None); } stream.Position = 0; using var objectReader = ObjectReader.TryGetReader(stream); var newText = serializer.Deserialize<SourceText>(sourceText.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None); Assert.Equal(sourceText.ToString(), newText.ToString()); } // test with wrong encoding that doesn't support serialization sourceText = SourceText.From("Hello", new NotSerializableEncoding()); using (var stream = SerializableBytes.CreateWritableStream()) { using var context = SolutionReplicationContext.Create(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { serializer.Serialize(sourceText, objectWriter, context, CancellationToken.None); } stream.Position = 0; using var objectReader = ObjectReader.TryGetReader(stream); var newText = serializer.Deserialize<SourceText>(sourceText.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None); Assert.Equal(sourceText.ToString(), newText.ToString()); } } [Fact] public void TestCompilationOptions_NullableAndImport() { var csharpOptions = CSharp.CSharpCompilation.Create("dummy").Options.WithNullableContextOptions(NullableContextOptions.Warnings).WithMetadataImportOptions(MetadataImportOptions.All); var vbOptions = VisualBasic.VisualBasicCompilation.Create("dummy").Options.WithMetadataImportOptions(MetadataImportOptions.Internal); using var workspace = CreateWorkspace(); var serializer = workspace.Services.GetService<ISerializerService>(); VerifyOptions(csharpOptions); VerifyOptions(vbOptions); void VerifyOptions(CompilationOptions originalOptions) { using var stream = SerializableBytes.CreateWritableStream(); using var context = SolutionReplicationContext.Create(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { serializer.Serialize(originalOptions, objectWriter, context, CancellationToken.None); } stream.Position = 0; using var objectReader = ObjectReader.TryGetReader(stream); var recoveredOptions = serializer.Deserialize<CompilationOptions>(originalOptions.GetWellKnownSynchronizationKind(), objectReader, CancellationToken.None); var original = serializer.CreateChecksum(originalOptions, CancellationToken.None); var recovered = serializer.CreateChecksum(recoveredOptions, CancellationToken.None); Assert.Equal(original, recovered); } } private static async Task VerifyOptionSetsAsync(Workspace workspace, Action<OptionSet> verifyOptionValues) { var solution = workspace.CurrentSolution; verifyOptionValues(workspace.Options); verifyOptionValues(solution.Options); var validator = new SerializationValidator(workspace.Services); using var scope = await validator.AssetStorage.StoreAssetsAsync(solution, CancellationToken.None).ConfigureAwait(false); var checksum = scope.SolutionInfo.SolutionChecksum; var solutionObject = await validator.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false); await validator.VerifyChecksumInServiceAsync(solutionObject.Attributes, WellKnownSynchronizationKind.SolutionAttributes); await validator.VerifyChecksumInServiceAsync(solutionObject.Options, WellKnownSynchronizationKind.OptionSet); var recoveredSolution = await validator.GetSolutionAsync(scope); // option should be exactly same Assert.Equal(0, recoveredSolution.Options.GetChangedOptions(workspace.Options).Count()); verifyOptionValues(workspace.Options); verifyOptionValues(recoveredSolution.Options); // checksum for recovered solution should be the same. using var recoveredScope = await validator.AssetStorage.StoreAssetsAsync(recoveredSolution, CancellationToken.None).ConfigureAwait(false); var recoveredChecksum = recoveredScope.SolutionInfo.SolutionChecksum; Assert.Equal(checksum, recoveredChecksum); } private static SolutionAsset CloneAsset(ISerializerService serializer, SolutionAsset asset) { using var stream = SerializableBytes.CreateWritableStream(); using var context = SolutionReplicationContext.Create(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { serializer.Serialize(asset.Value, writer, context, CancellationToken.None); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); var recovered = serializer.Deserialize<object>(asset.Kind, reader, CancellationToken.None); var assetFromStorage = new SolutionAsset(serializer.CreateChecksum(recovered, CancellationToken.None), recovered); Assert.Equal(asset.Checksum, assetFromStorage.Checksum); return assetFromStorage; } private static AnalyzerFileReference CreateShadowCopiedAnalyzerReference(TempRoot tempRoot) { // use 2 different files as shadow copied content var original = typeof(AdhocWorkspace).Assembly.Location; var shadow = tempRoot.CreateFile("shadow", "dll"); shadow.CopyContentFrom(typeof(object).Assembly.Location); return new AnalyzerFileReference(original, new MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string>.Empty.Add(original, shadow.Path))); } private class MissingAnalyzerLoader : AnalyzerAssemblyLoader { protected override Assembly LoadFromPathUncheckedImpl(string fullPath) => throw new FileNotFoundException(fullPath); } private class MissingMetadataReference : PortableExecutableReference { public MissingMetadataReference() : base(MetadataReferenceProperties.Assembly, "missing_reference", XmlDocumentationProvider.Default) { } protected override DocumentationProvider CreateDocumentationProvider() => null; protected override Metadata GetMetadataImpl() => throw new FileNotFoundException("can't find"); protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) => this; } private class MockShadowCopyAnalyzerAssemblyLoader : IAnalyzerAssemblyLoader { private readonly ImmutableDictionary<string, string> _map; public MockShadowCopyAnalyzerAssemblyLoader(ImmutableDictionary<string, string> map) => _map = map; public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) => Assembly.LoadFrom(_map[fullPath]); } private class NotSerializableEncoding : Encoding { private readonly Encoding _real = Encoding.UTF8; public override string WebName => _real.WebName; public override int GetByteCount(char[] chars, int index, int count) => _real.GetByteCount(chars, index, count); public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) => GetBytes(chars, charIndex, charCount, bytes, byteIndex); public override int GetCharCount(byte[] bytes, int index, int count) => GetCharCount(bytes, index, count); public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) => GetChars(bytes, byteIndex, byteCount, chars, charIndex); public override int GetMaxByteCount(int charCount) => GetMaxByteCount(charCount); public override int GetMaxCharCount(int byteCount) => GetMaxCharCount(byteCount); } } }
1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Workspaces/Core/Portable/Formatting/FormattingBehaviorOptions.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.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// Solution-wide formatting options. /// </summary> internal sealed class FormattingBehaviorOptions { [ExportSolutionOptionProvider, Shared] internal sealed class Provider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Provider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( SmartIndent, PreferredWrappingColumn, AllowDisjointSpanMerging, AutoFormattingOnReturn, AutoFormattingOnTyping, AutoFormattingOnSemicolon, FormatOnPaste); } private const string FeatureName = "FormattingOptions"; // This is also serialized by the Visual Studio-specific LanguageSettingsPersister public static PerLanguageOption2<FormattingOptions.IndentStyle> SmartIndent { get; } = new(FeatureName, FormattingOptionGroups.IndentationAndSpacing, nameof(SmartIndent), defaultValue: FormattingOptions.IndentStyle.Smart); /// <summary> /// Default value of 120 was picked based on the amount of code in a github.com diff at 1080p. /// That resolution is the most common value as per the last DevDiv survey as well as the latest /// Steam hardware survey. This also seems to a reasonable length default in that shorter /// lengths can often feel too cramped for .NET languages, which are often starting with a /// default indentation of at least 16 (for namespace, class, member, plus the final construct /// indentation). /// /// TODO: Currently the option has no storage and always has its default value. See https://github.com/dotnet/roslyn/pull/30422#issuecomment-436118696. /// </summary> internal static Option2<int> PreferredWrappingColumn { get; } = new(FeatureName, FormattingOptionGroups.NewLine, nameof(PreferredWrappingColumn), defaultValue: 120); /// <summary> /// TODO: Currently the option has no storage and always has its default value. /// </summary> internal static Option2<bool> AllowDisjointSpanMerging { get; } = new(FeatureName, OptionGroup.Default, nameof(AllowDisjointSpanMerging), defaultValue: false); internal static readonly PerLanguageOption2<bool> AutoFormattingOnReturn = new(FeatureName, OptionGroup.Default, nameof(AutoFormattingOnReturn), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Return")); public static readonly PerLanguageOption2<bool> AutoFormattingOnTyping = new(FeatureName, OptionGroup.Default, nameof(AutoFormattingOnTyping), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Typing")); public static readonly PerLanguageOption2<bool> AutoFormattingOnSemicolon = new(FeatureName, OptionGroup.Default, nameof(AutoFormattingOnSemicolon), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Semicolon")); public static readonly PerLanguageOption2<bool> FormatOnPaste = new(FeatureName, OptionGroup.Default, nameof(FormatOnPaste), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.FormatOnPaste")); } }
// 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.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// Solution-wide formatting options. /// </summary> internal sealed class FormattingBehaviorOptions { [ExportSolutionOptionProvider, Shared] internal sealed class Provider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Provider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( SmartIndent, PreferredWrappingColumn, AllowDisjointSpanMerging, AutoFormattingOnReturn, AutoFormattingOnTyping, AutoFormattingOnSemicolon, FormatOnPaste); } private const string FeatureName = "FormattingOptions"; // This is also serialized by the Visual Studio-specific LanguageSettingsPersister public static PerLanguageOption2<FormattingOptions.IndentStyle> SmartIndent { get; } = new(FeatureName, FormattingOptionGroups.IndentationAndSpacing, nameof(SmartIndent), defaultValue: FormattingOptions.IndentStyle.Smart); /// <summary> /// Default value of 120 was picked based on the amount of code in a github.com diff at 1080p. /// That resolution is the most common value as per the last DevDiv survey as well as the latest /// Steam hardware survey. This also seems to a reasonable length default in that shorter /// lengths can often feel too cramped for .NET languages, which are often starting with a /// default indentation of at least 16 (for namespace, class, member, plus the final construct /// indentation). /// /// TODO: Currently the option has no storage and always has its default value. See https://github.com/dotnet/roslyn/pull/30422#issuecomment-436118696. /// </summary> internal static Option2<int> PreferredWrappingColumn { get; } = new(FeatureName, FormattingOptionGroups.NewLine, nameof(PreferredWrappingColumn), defaultValue: 120); /// <summary> /// TODO: Currently the option has no storage and always has its default value. /// </summary> internal static Option2<bool> AllowDisjointSpanMerging { get; } = new(FeatureName, OptionGroup.Default, nameof(AllowDisjointSpanMerging), defaultValue: false); internal static readonly PerLanguageOption2<bool> AutoFormattingOnReturn = new(FeatureName, OptionGroup.Default, nameof(AutoFormattingOnReturn), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Return")); public static readonly PerLanguageOption2<bool> AutoFormattingOnTyping = new(FeatureName, OptionGroup.Default, nameof(AutoFormattingOnTyping), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Typing")); public static readonly PerLanguageOption2<bool> AutoFormattingOnSemicolon = new(FeatureName, OptionGroup.Default, nameof(AutoFormattingOnSemicolon), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Semicolon")); public static readonly PerLanguageOption2<bool> FormatOnPaste = new(FeatureName, OptionGroup.Default, nameof(FormatOnPaste), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.FormatOnPaste")); } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpErrorListNetCore.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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpErrorListNetCore : CSharpErrorListCommon { public CSharpErrorListNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(false); // The CSharpNetCoreClassLibrary template does not open a file automatically. VisualStudio.SolutionExplorer.OpenFile(new Project(ProjectName), WellKnownProjectTemplates.CSharpNetCoreClassLibraryClassFileName); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorList() { base.ErrorList(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorLevelWarning() { base.ErrorLevelWarning(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] [WorkItem(39902, "https://github.com/dotnet/roslyn/issues/39902")] public override void ErrorsAfterClosingFile() { base.ErrorsAfterClosingFile(); } } }
// 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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpErrorListNetCore : CSharpErrorListCommon { public CSharpErrorListNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(false); // The CSharpNetCoreClassLibrary template does not open a file automatically. VisualStudio.SolutionExplorer.OpenFile(new Project(ProjectName), WellKnownProjectTemplates.CSharpNetCoreClassLibraryClassFileName); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorList() { base.ErrorList(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorLevelWarning() { base.ErrorLevelWarning(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] [WorkItem(39902, "https://github.com/dotnet/roslyn/issues/39902")] public override void ErrorsAfterClosingFile() { base.ErrorsAfterClosingFile(); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/Core/Portable/StackTraceExplorer/IgnoredFrame.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.StackTraceExplorer { internal sealed class IgnoredFrame : ParsedFrame { public IgnoredFrame(string originalText) : base(originalText) { } } }
// 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.StackTraceExplorer { internal sealed class IgnoredFrame : ParsedFrame { public IgnoredFrame(string originalText) : base(originalText) { } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Workspaces/MSBuildTest/Resources/NetCoreMultiTFM/Program.cs
using System; namespace NetCoreApp2 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
using System; namespace NetCoreApp2 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionTests.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.SimplifyLinqExpression; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.SimplifyLinqExpression { using VerifyCS = CSharpCodeFixVerifier< CSharpSimplifyLinqExpressionDiagnosticAnalyzer, CSharpSimplifyLinqExpressionCodeFixProvider>; public partial class CSharpSimplifyLinqExpressionTests { [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public static async Task TestAllowedMethodTypes( [CombinatorialValues( "x => x==1", "(x) => x==1", "x => { return x==1; }", "(x) => { return x==1; }")] string lambda, [CombinatorialValues( "First", "Last", "Single", "Any", "Count", "SingleOrDefault", "FirstOrDefault", "LastOrDefault")] string methodName) { await new VerifyCS.Test { TestCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void Main() {{ static IEnumerable<int> Data() {{ yield return 1; yield return 2; }} var test = [|Data().Where({lambda}).{methodName}()|]; }} }}", FixedCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void Main() {{ static IEnumerable<int> Data() {{ yield return 1; yield return 2; }} var test = Data().{methodName}({lambda}); }} }}" }.RunAsync(); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public static async Task TestWhereWithIndexMethodTypes( [CombinatorialValues( "(x, index) => x==index", "(x, index) => { return x==index; }")] string lambda, [CombinatorialValues( "First", "Last", "Single", "Any", "Count", "SingleOrDefault", "FirstOrDefault", "LastOrDefault")] string methodName) { var testCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void Main() {{ static IEnumerable<int> Data() {{ yield return 1; yield return 2; }} var test = Data().Where({lambda}).{methodName}(); }} }}"; await VerifyCS.VerifyAnalyzerAsync(testCode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public async Task TestQueryComprehensionSyntax( [CombinatorialValues( "x => x==1", "x => { return x==1; }")] string lambda, [CombinatorialValues( "First", "Last", "Single", "Any", "Count", "SingleOrDefault", "FirstOrDefault", "LastOrDefault")] string methodName) { await new VerifyCS.Test { TestCode = $@" using System.Linq; class Test {{ static void M() {{ var test1 = [|(from value in Enumerable.Range(0, 10) select value).Where({lambda}).{methodName}()|]; }} }}", FixedCode = $@" using System.Linq; class Test {{ static void M() {{ var test1 = (from value in Enumerable.Range(0, 10) select value).{methodName}({lambda}); }} }}" }.RunAsync(); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] [InlineData("First")] [InlineData("Last")] [InlineData("Single")] [InlineData("Any")] [InlineData("Count")] [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] public async Task TestMultiLineLambda(string methodName) { await new VerifyCS.Test { TestCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void Main() {{ static IEnumerable<int> Data() {{ yield return 1; yield return 2; }} var test = [|Data().Where(x => {{ Console.Write(x); return x == 1; }}).{methodName}()|]; }} }}", FixedCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void Main() {{ static IEnumerable<int> Data() {{ yield return 1; yield return 2; }} var test = Data().{methodName}(x => {{ Console.Write(x); return x == 1; }}); }} }}" }.RunAsync(); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] [InlineData("First", "string")] [InlineData("Last", "string")] [InlineData("Single", "string")] [InlineData("Any", "bool")] [InlineData("Count", "int")] [InlineData("SingleOrDefault", "string")] [InlineData("FirstOrDefault", "string")] [InlineData("LastOrDefault", "string")] public async Task TestOutsideFunctionCallLambda(string methodName, string returnType) { await new VerifyCS.Test { TestCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ public static bool FooTest(string input) {{ return true; }} static IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }}; {returnType} result = [|test.Where(x => FooTest(x)).{methodName}()|]; }}", FixedCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ public static bool FooTest(string input) {{ return true; }} static IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }}; {returnType} result = test.{methodName}(x => FooTest(x)); }}" }.RunAsync(); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] [InlineData("First")] [InlineData("Last")] [InlineData("Single")] [InlineData("Any")] [InlineData("Count")] [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] public async Task TestQueryableIsNotConsidered(string methodName) { var source = $@" using System; using System.Linq; using System.Collections.Generic; namespace demo {{ class Test {{ void M() {{ List<int> testvar1 = new List<int> {{ 1, 2, 3, 4, 5, 6, 7, 8 }}; IQueryable<int> testvar2 = testvar1.AsQueryable().Where(x => x % 2 == 0); var output = testvar2.Where(x => x == 4).{methodName}(); }} }} }}"; await VerifyCS.VerifyAnalyzerAsync(source); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public async Task TestNestedLambda( [CombinatorialValues( "First", "Last", "Single", "Any", "Count", "SingleOrDefault", "FirstOrDefault", "LastOrDefault")] string firstMethod, [CombinatorialValues( "First", "Last", "Single", "Any", "Count", "SingleOrDefault", "FirstOrDefault", "LastOrDefault")] string secondMethod) { var testCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ void M() {{ IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }}; var test5 = [|test.Where(a => [|a.Where(s => s.Equals(""hello"")).{secondMethod}()|].Equals(""hello"")).{firstMethod}()|]; }} }}"; var fixedCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ void M() {{ IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }}; var test5 = test.{firstMethod}(a => a.{secondMethod}(s => s.Equals(""hello"")).Equals(""hello"")); }} }}"; await VerifyCS.VerifyCodeFixAsync( testCode, fixedCode); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] [InlineData("First")] [InlineData("Last")] [InlineData("Single")] [InlineData("Any")] [InlineData("Count")] [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] public async Task TestExplicitEnumerableCall(string methodName) { await new VerifyCS.Test { TestCode = $@" using System; using System.Linq; using System.Collections.Generic; using System.Linq.Expressions; class Test {{ static void Main() {{ IEnumerable<int> test = new List<int> {{ 1, 2, 3, 4, 5}}; [|Enumerable.Where(test, (x => x == 1)).{methodName}()|]; }} }}", FixedCode = $@" using System; using System.Linq; using System.Collections.Generic; using System.Linq.Expressions; class Test {{ static void Main() {{ IEnumerable<int> test = new List<int> {{ 1, 2, 3, 4, 5}}; Enumerable.{methodName}(test, (x => x == 1)); }} }}" }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public async Task TestUserDefinedWhere() { var source = @" using System; using System.Linq; using System.Collections.Generic; namespace demo { class Test { public class TestClass4 { private string test; public TestClass4() => test = ""hello""; public TestClass4 Where(Func<string, bool> input) { return this; } public string Single() { return test; } } static void Main() { TestClass4 Test1 = new TestClass4(); TestClass4 test = Test1.Where(y => true); } } }"; await VerifyCS.VerifyAnalyzerAsync(source); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] [InlineData("First")] [InlineData("Last")] [InlineData("Single")] [InlineData("Any")] [InlineData("Count")] [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] public async Task TestArgumentsInSecondCall(string methodName) { var source = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void M() {{ IEnumerable<string> test1 = new List<string>{{ ""hello"", ""world"", ""!"" }}; var test2 = test1.Where(x => x == ""!"").{methodName}(x => x.Length == 1); }} }}"; await VerifyCS.VerifyAnalyzerAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public async Task TestUnsupportedFunction() { var source = @" using System; using System.Linq; using System.Collections.Generic; namespace demo { class Test { static List<int> test1 = new List<int> { 3, 12, 4, 6, 20 }; int test2 = test1.Where(x => x > 0).Count(); } }"; await VerifyCS.VerifyAnalyzerAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public async Task TestExpressionTreeInput() { var source = @" using System; using System.Linq; using System.Collections.Generic; using System.Linq.Expressions; class Test { void Main() { string[] places = { ""Beach"", ""Pool"", ""Store"", ""House"", ""Car"", ""Salon"", ""Mall"", ""Mountain""}; IQueryable<String> queryableData = places.AsQueryable<string>(); ParameterExpression pe = Expression.Parameter(typeof(string), ""place""); Expression left = Expression.Call(pe, typeof(string).GetMethod(""ToLower"", System.Type.EmptyTypes)); Expression right = Expression.Constant(""coho winery""); Expression e1 = Expression.Equal(left, right); left = Expression.Property(pe, typeof(string).GetProperty(""Length"")); right = Expression.Constant(16, typeof(int)); Expression e2 = Expression.GreaterThan(left, right); Expression predicateBody = Expression.OrElse(e1, e2); Expression<Func<int, bool>> lambda1 = num => num < 5; string result = queryableData.Where(Expression.Lambda<Func<string, bool>>(predicateBody, new ParameterExpression[] { pe })).First(); } }"; await VerifyCS.VerifyAnalyzerAsync(source); } } }
// 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.SimplifyLinqExpression; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.SimplifyLinqExpression { using VerifyCS = CSharpCodeFixVerifier< CSharpSimplifyLinqExpressionDiagnosticAnalyzer, CSharpSimplifyLinqExpressionCodeFixProvider>; public partial class CSharpSimplifyLinqExpressionTests { [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public static async Task TestAllowedMethodTypes( [CombinatorialValues( "x => x==1", "(x) => x==1", "x => { return x==1; }", "(x) => { return x==1; }")] string lambda, [CombinatorialValues( "First", "Last", "Single", "Any", "Count", "SingleOrDefault", "FirstOrDefault", "LastOrDefault")] string methodName) { await new VerifyCS.Test { TestCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void Main() {{ static IEnumerable<int> Data() {{ yield return 1; yield return 2; }} var test = [|Data().Where({lambda}).{methodName}()|]; }} }}", FixedCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void Main() {{ static IEnumerable<int> Data() {{ yield return 1; yield return 2; }} var test = Data().{methodName}({lambda}); }} }}" }.RunAsync(); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public static async Task TestWhereWithIndexMethodTypes( [CombinatorialValues( "(x, index) => x==index", "(x, index) => { return x==index; }")] string lambda, [CombinatorialValues( "First", "Last", "Single", "Any", "Count", "SingleOrDefault", "FirstOrDefault", "LastOrDefault")] string methodName) { var testCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void Main() {{ static IEnumerable<int> Data() {{ yield return 1; yield return 2; }} var test = Data().Where({lambda}).{methodName}(); }} }}"; await VerifyCS.VerifyAnalyzerAsync(testCode); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public async Task TestQueryComprehensionSyntax( [CombinatorialValues( "x => x==1", "x => { return x==1; }")] string lambda, [CombinatorialValues( "First", "Last", "Single", "Any", "Count", "SingleOrDefault", "FirstOrDefault", "LastOrDefault")] string methodName) { await new VerifyCS.Test { TestCode = $@" using System.Linq; class Test {{ static void M() {{ var test1 = [|(from value in Enumerable.Range(0, 10) select value).Where({lambda}).{methodName}()|]; }} }}", FixedCode = $@" using System.Linq; class Test {{ static void M() {{ var test1 = (from value in Enumerable.Range(0, 10) select value).{methodName}({lambda}); }} }}" }.RunAsync(); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] [InlineData("First")] [InlineData("Last")] [InlineData("Single")] [InlineData("Any")] [InlineData("Count")] [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] public async Task TestMultiLineLambda(string methodName) { await new VerifyCS.Test { TestCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void Main() {{ static IEnumerable<int> Data() {{ yield return 1; yield return 2; }} var test = [|Data().Where(x => {{ Console.Write(x); return x == 1; }}).{methodName}()|]; }} }}", FixedCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void Main() {{ static IEnumerable<int> Data() {{ yield return 1; yield return 2; }} var test = Data().{methodName}(x => {{ Console.Write(x); return x == 1; }}); }} }}" }.RunAsync(); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] [InlineData("First", "string")] [InlineData("Last", "string")] [InlineData("Single", "string")] [InlineData("Any", "bool")] [InlineData("Count", "int")] [InlineData("SingleOrDefault", "string")] [InlineData("FirstOrDefault", "string")] [InlineData("LastOrDefault", "string")] public async Task TestOutsideFunctionCallLambda(string methodName, string returnType) { await new VerifyCS.Test { TestCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ public static bool FooTest(string input) {{ return true; }} static IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }}; {returnType} result = [|test.Where(x => FooTest(x)).{methodName}()|]; }}", FixedCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ public static bool FooTest(string input) {{ return true; }} static IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }}; {returnType} result = test.{methodName}(x => FooTest(x)); }}" }.RunAsync(); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] [InlineData("First")] [InlineData("Last")] [InlineData("Single")] [InlineData("Any")] [InlineData("Count")] [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] public async Task TestQueryableIsNotConsidered(string methodName) { var source = $@" using System; using System.Linq; using System.Collections.Generic; namespace demo {{ class Test {{ void M() {{ List<int> testvar1 = new List<int> {{ 1, 2, 3, 4, 5, 6, 7, 8 }}; IQueryable<int> testvar2 = testvar1.AsQueryable().Where(x => x % 2 == 0); var output = testvar2.Where(x => x == 4).{methodName}(); }} }} }}"; await VerifyCS.VerifyAnalyzerAsync(source); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public async Task TestNestedLambda( [CombinatorialValues( "First", "Last", "Single", "Any", "Count", "SingleOrDefault", "FirstOrDefault", "LastOrDefault")] string firstMethod, [CombinatorialValues( "First", "Last", "Single", "Any", "Count", "SingleOrDefault", "FirstOrDefault", "LastOrDefault")] string secondMethod) { var testCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ void M() {{ IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }}; var test5 = [|test.Where(a => [|a.Where(s => s.Equals(""hello"")).{secondMethod}()|].Equals(""hello"")).{firstMethod}()|]; }} }}"; var fixedCode = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ void M() {{ IEnumerable<string> test = new List<string> {{ ""hello"", ""world"", ""!"" }}; var test5 = test.{firstMethod}(a => a.{secondMethod}(s => s.Equals(""hello"")).Equals(""hello"")); }} }}"; await VerifyCS.VerifyCodeFixAsync( testCode, fixedCode); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] [InlineData("First")] [InlineData("Last")] [InlineData("Single")] [InlineData("Any")] [InlineData("Count")] [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] public async Task TestExplicitEnumerableCall(string methodName) { await new VerifyCS.Test { TestCode = $@" using System; using System.Linq; using System.Collections.Generic; using System.Linq.Expressions; class Test {{ static void Main() {{ IEnumerable<int> test = new List<int> {{ 1, 2, 3, 4, 5}}; [|Enumerable.Where(test, (x => x == 1)).{methodName}()|]; }} }}", FixedCode = $@" using System; using System.Linq; using System.Collections.Generic; using System.Linq.Expressions; class Test {{ static void Main() {{ IEnumerable<int> test = new List<int> {{ 1, 2, 3, 4, 5}}; Enumerable.{methodName}(test, (x => x == 1)); }} }}" }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public async Task TestUserDefinedWhere() { var source = @" using System; using System.Linq; using System.Collections.Generic; namespace demo { class Test { public class TestClass4 { private string test; public TestClass4() => test = ""hello""; public TestClass4 Where(Func<string, bool> input) { return this; } public string Single() { return test; } } static void Main() { TestClass4 Test1 = new TestClass4(); TestClass4 test = Test1.Where(y => true); } } }"; await VerifyCS.VerifyAnalyzerAsync(source); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] [InlineData("First")] [InlineData("Last")] [InlineData("Single")] [InlineData("Any")] [InlineData("Count")] [InlineData("SingleOrDefault")] [InlineData("FirstOrDefault")] [InlineData("LastOrDefault")] public async Task TestArgumentsInSecondCall(string methodName) { var source = $@" using System; using System.Linq; using System.Collections.Generic; class Test {{ static void M() {{ IEnumerable<string> test1 = new List<string>{{ ""hello"", ""world"", ""!"" }}; var test2 = test1.Where(x => x == ""!"").{methodName}(x => x.Length == 1); }} }}"; await VerifyCS.VerifyAnalyzerAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public async Task TestUnsupportedFunction() { var source = @" using System; using System.Linq; using System.Collections.Generic; namespace demo { class Test { static List<int> test1 = new List<int> { 3, 12, 4, 6, 20 }; int test2 = test1.Where(x => x > 0).Count(); } }"; await VerifyCS.VerifyAnalyzerAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyLinqExpression)] public async Task TestExpressionTreeInput() { var source = @" using System; using System.Linq; using System.Collections.Generic; using System.Linq.Expressions; class Test { void Main() { string[] places = { ""Beach"", ""Pool"", ""Store"", ""House"", ""Car"", ""Salon"", ""Mall"", ""Mountain""}; IQueryable<String> queryableData = places.AsQueryable<string>(); ParameterExpression pe = Expression.Parameter(typeof(string), ""place""); Expression left = Expression.Call(pe, typeof(string).GetMethod(""ToLower"", System.Type.EmptyTypes)); Expression right = Expression.Constant(""coho winery""); Expression e1 = Expression.Equal(left, right); left = Expression.Property(pe, typeof(string).GetProperty(""Length"")); right = Expression.Constant(16, typeof(int)); Expression e2 = Expression.GreaterThan(left, right); Expression predicateBody = Expression.OrElse(e1, e2); Expression<Func<int, bool>> lambda1 = num => num < 5; string result = queryableData.Where(Expression.Lambda<Func<string, bool>>(predicateBody, new ParameterExpression[] { pe })).First(); } }"; await VerifyCS.VerifyAnalyzerAsync(source); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IIsPatternExpression.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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IIsPatternExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_VarPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; if (/*<bind>*/x is var y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is var y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32?, NarrowedType: System.Int32?, DeclaredSymbol: System.Int32? y, MatchesNull: True) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_PrimitiveTypePatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; if (/*<bind>*/x is int y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is int y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_ReferenceTypePatternDeclaration() { string source = @" using System; class X { void M(X x) { if (/*<bind>*/x is X y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is X y') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: X) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: X, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_TypeParameterTypePatternDeclaration() { string source = @" using System; class X { void M<T>(T x) where T: class { if (/*<bind>*/x is T y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is T y') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'T y') (InputType: T, NarrowedType: T, DeclaredSymbol: T y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_DynamicTypePatternDeclaration() { string source = @" using System; class X { void M(X x) { if (/*<bind>*/x is dynamic y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is dynamic y') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: X) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'dynamic y') (InputType: X, NarrowedType: dynamic, DeclaredSymbol: dynamic y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS8208: It is not legal to use the type 'dynamic' in a pattern. // if (/*<bind>*/x is dynamic y/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_PatternDynamicType, "dynamic").WithLocation(7, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_ConstantPattern() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is 12/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is 12') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '12') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_ConstantPatternWithConversion() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is (int)12.0/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is (int)12.0') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '(int)12.0') (InputType: System.Int32?, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 12) (Syntax: '(int)12.0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 12) (Syntax: '12.0') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_ConstantPatternWithNoImplicitConversion() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is 12.0/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is 12.0') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '12.0') (InputType: System.Int32?, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 12, IsInvalid, IsImplicit) (Syntax: '12.0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 12, IsInvalid) (Syntax: '12.0') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0266: Cannot implicitly convert type 'double' to 'int?'. An explicit conversion exists (are you missing a cast?) // if (/*<bind>*/x is 12.0/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "12.0").WithArguments("double", "int?").WithLocation(8, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_ConstantPatternWithNoValidImplicitOrExplicitConversion() { string source = @" using System; class X { void M() { int x = 12, y = 12; if (/*<bind>*/x is null/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is null') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: 'null') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0037: Cannot convert null to 'int' because it is a non-nullable value type // if (/*<bind>*/x is null/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_UndefinedTypeInPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; if (/*<bind>*/x is UndefinedType y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is UndefinedType y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'UndefinedType y') (InputType: System.Int32?, NarrowedType: UndefinedType, DeclaredSymbol: UndefinedType y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) // if (/*<bind>*/x is UndefinedType y/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndefinedType").WithArguments("UndefinedType").WithLocation(8, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidConstantPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'y') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32?, IsInvalid) (Syntax: 'y') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0150: A constant value is expected // if (/*<bind>*/x is y/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_ConstantExpected, "y").WithLocation(8, 28) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidTypeInPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; if (/*<bind>*/x is X y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is X y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'X y') (InputType: System.Int32?, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS8121: An expression of type 'int?' cannot be handled by a pattern of type 'X'. // if (/*<bind>*/x is X y/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_PatternWrongType, "X").WithArguments("int?", "X").WithLocation(8, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_DuplicateLocalInPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is int y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is int y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int y') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0128: A local variable or function named 'y' is already defined in this scope // if (/*<bind>*/x is int y/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_LocalDuplicate, "y").WithArguments("y").WithLocation(8, 32) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidMultipleLocalsInPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is int y2') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y2') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y2, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1026: ) expected // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_CloseParenExpected, ",").WithLocation(8, 45), // CS1525: Invalid expression term ',' // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(8, 45), // CS1002: ; expected // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_SemicolonExpected, ",").WithLocation(8, 45), // CS1513: } expected // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_RbraceExpected, ",").WithLocation(8, 45), // CS1002: ; expected // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 49), // CS1513: } expected // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 49), // CS0103: The name 'y3' does not exist in the current context // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_NameNotInContext, "y3").WithArguments("y3").WithLocation(8, 47) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidConstDeclarationInPatternDeclaration() { string source = @" using System; class X { void M() { int x = 12; if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean, IsInvalid) (Syntax: 'x is /*</bind>*/') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') IsType: ? "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,39): error CS1525: Invalid expression term 'const' // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "const").WithArguments("const").WithLocation(8, 39), // file.cs(8,39): error CS1026: ) expected // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_CloseParenExpected, "const").WithLocation(8, 39), // file.cs(8,49): error CS0145: A const field requires a value to be provided // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_ConstValueRequired, "y").WithLocation(8, 49), // file.cs(8,50): error CS1002: ; expected // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 50), // file.cs(8,50): error CS1513: } expected // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 50), // file.cs(8,39): error CS1023: Embedded statement cannot be a declaration or labeled statement // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "const int y").WithLocation(8, 39), // file.cs(8,70): error CS0103: The name 'y' does not exist in the current context // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(8, 70), // file.cs(8,49): warning CS0168: The variable 'y' is declared but never used // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(8, 49) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidInDefaultParameterInitializer() { string source = @" using System; class X { void M(string x = /*<bind>*/string.Empty is string y/*</bind>*/) { } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'string.Empty is string y') Value: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'string y') (InputType: System.String, NarrowedType: System.String, DeclaredSymbol: System.String y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1736: Default parameter value for 'x' must be a compile-time constant // void M(string x = /*<bind>*/string.Empty is string y/*</bind>*/) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "string.Empty is string y").WithArguments("x").WithLocation(5, 33) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidInFieldInitializer() { string source = @" class C { private readonly static object o = 1; private readonly bool b = /*<bind>*/o is int x/*</bind>*/ && x >= 5; } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is int x') Value: IFieldReferenceOperation: System.Object C.o (Static) (OperationKind.FieldReference, Type: System.Object) (Syntax: 'o') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidInConstructorInitializer() { string source = @" class C { public C(object o): this (/*<bind>*/o is int x/*</bind>*/ && x >= 5) { } public C (bool b) { } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is int x') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidInAttributeArgument() { string source = @" class A: System.Attribute { public A (bool i) { } } [A(/*<bind>*/o is int x/*</bind>*/ && x >= 5)] class C { private const object o = 1; } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is int x') Value: IFieldReferenceOperation: System.Object C.o (Static) (OperationKind.FieldReference, Type: System.Object, Constant: 1, IsInvalid) (Syntax: 'o') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0134: 'C.o' is of type 'object'. A const field of a reference type other than string can only be initialized with null. // private const object o = 1; Diagnostic(ErrorCode.ERR_NotNullConstRefField, "1").WithArguments("C.o", "object").WithLocation(12, 30), // CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(/*<bind>*/o is int x/*</bind>*/ && x >= 5)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "o is int x/*</bind>*/ && x >= 5").WithLocation(9, 14) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_NoControlFlow_01() { string source = @" class C { void M(int? x, bool b, int x2, bool b2) /*<bind>*/{ b = x is var y; b2 = x2 is 1; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32? y] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = x is var y;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = x is var y') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is var y') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32?, NarrowedType: System.Int32?, DeclaredSymbol: System.Int32? y, MatchesNull: True) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b2 = x2 is 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b2 = x2 is 1') Left: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b2') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x2 is 1') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_NoControlFlow_02() { string source = @" class C { void M((int X, int Y)? x, bool b) /*<bind>*/{ b = x is (1, _) { Item1: var z } p; }/*</bind>*/ } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedOperationTree = @" IBlockOperation (1 statements, 2 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: (System.Int32 X, System.Int32 Y) p Local_2: System.Int32 z IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = x is (1 ... var z } p;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = x is (1 ... : var z } p') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is (1, _) ... : var z } p') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32 X, System.Int32 Y)?) (Syntax: 'x') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(1, _) { It ... : var z } p') (InputType: (System.Int32 X, System.Int32 Y)?, NarrowedType: (System.Int32 X, System.Int32 Y), DeclaredSymbol: (System.Int32 X, System.Int32 Y) p, MatchedType: (System.Int32 X, System.Int32 Y), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Item1: var z') Member: IFieldReferenceOperation: System.Int32 (System.Int32 X, System.Int32 Y).Item1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Item1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 X, System.Int32 Y), IsImplicit) (Syntax: 'Item1') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: True) "; VerifyOperationTreeForTest<BlockSyntax>(compilation, expectedOperationTree); string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [(System.Int32 X, System.Int32 Y) p] [System.Int32 z] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = x is (1 ... var z } p;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = x is (1 ... : var z } p') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is (1, _) ... : var z } p') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32 X, System.Int32 Y)?) (Syntax: 'x') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(1, _) { It ... : var z } p') (InputType: (System.Int32 X, System.Int32 Y)?, NarrowedType: (System.Int32 X, System.Int32 Y), DeclaredSymbol: (System.Int32 X, System.Int32 Y) p, MatchedType: (System.Int32 X, System.Int32 Y), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Item1: var z') Member: IFieldReferenceOperation: System.Int32 (System.Int32 X, System.Int32 Y).Item1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Item1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 X, System.Int32 Y), IsImplicit) (Syntax: 'Item1') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: True) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedFlowGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_NoControlFlow_03() { string source = @" class C { void M((int X, (int Y, int Z))? tuple, bool b) /*<bind>*/{ b = tuple is (1, _) { Item1: var x, Item2: { Y: 1, Z: var z } } p; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [(System.Int32 X, (System.Int32 Y, System.Int32 Z)) p] [System.Int32 x] [System.Int32 z] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = tuple i ... ar z } } p;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = tuple i ... var z } } p') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'tuple is (1 ... var z } } p') Value: IParameterReferenceOperation: tuple (OperationKind.ParameterReference, Type: (System.Int32 X, (System.Int32 Y, System.Int32 Z))?) (Syntax: 'tuple') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(1, _) { It ... var z } } p') (InputType: (System.Int32 X, (System.Int32 Y, System.Int32 Z))?, NarrowedType: (System.Int32 X, (System.Int32 Y, System.Int32 Z)), DeclaredSymbol: (System.Int32 X, (System.Int32 Y, System.Int32 Z)) p, MatchedType: (System.Int32 X, (System.Int32 Y, System.Int32 Z)), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: (System.Int32 Y, System.Int32 Z), NarrowedType: (System.Int32 Y, System.Int32 Z)) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Item1: var x') Member: IFieldReferenceOperation: System.Int32 (System.Int32 X, (System.Int32 Y, System.Int32 Z)).Item1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Item1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 X, (System.Int32 Y, System.Int32 Z)), IsImplicit) (Syntax: 'Item1') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var x') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: True) IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Item2: { Y: ... Z: var z }') Member: IFieldReferenceOperation: (System.Int32 Y, System.Int32 Z) (System.Int32 X, (System.Int32 Y, System.Int32 Z)).Item2 (OperationKind.FieldReference, Type: (System.Int32 Y, System.Int32 Z)) (Syntax: 'Item2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 X, (System.Int32 Y, System.Int32 Z)), IsImplicit) (Syntax: 'Item2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Y: 1, Z: var z }') (InputType: (System.Int32 Y, System.Int32 Z), NarrowedType: (System.Int32 Y, System.Int32 Z), DeclaredSymbol: null, MatchedType: (System.Int32 Y, System.Int32 Z), DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Y: 1') Member: IFieldReferenceOperation: System.Int32 (System.Int32 Y, System.Int32 Z).Y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 Y, System.Int32 Z), IsImplicit) (Syntax: 'Y') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Z: var z') Member: IFieldReferenceOperation: System.Int32 (System.Int32 Y, System.Int32 Z).Z (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Z') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 Y, System.Int32 Z), IsImplicit) (Syntax: 'Z') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: True) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_ControlFlowInValue() { string source = @" class C { void M(int? x1, int x2, bool b) /*<bind>*/{ b = (x1 ?? x2) is var y; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 y] CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'x1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = (x1 ?? x2) is var y;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = (x1 ?? x2) is var y') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '(x1 ?? x2) is var y') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x1 ?? x2') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: True) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_RecursivePattern() { string source = @" class C { void M((int X, int Y) tuple, bool b) { if (/*<bind>*/tuple is (1, 2) { Item1: int x } y/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'tuple is (1 ... : int x } y') Value: IParameterReferenceOperation: tuple (OperationKind.ParameterReference, Type: (System.Int32 X, System.Int32 Y)) (Syntax: 'tuple') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(1, 2) { It ... : int x } y') (InputType: (System.Int32 X, System.Int32 Y), NarrowedType: (System.Int32 X, System.Int32 Y), DeclaredSymbol: (System.Int32 X, System.Int32 Y) y, MatchedType: (System.Int32 X, System.Int32 Y), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '2') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Item1: int x') Member: IFieldReferenceOperation: System.Int32 (System.Int32 X, System.Int32 Y).Item1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Item1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 X, System.Int32 Y), IsImplicit) (Syntax: 'Item1') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_RecursivePatternWithNestedPropertyPatterns() { string source = @" class C { C field; C prop { get; } void M() { if (/*<bind>*/this is { prop.field: null }/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'this is { p ... eld: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ prop.field: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'prop') Member: IPropertyReferenceOperation: C C.prop { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'prop') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'prop') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'prop') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'prop.field') Member: IFieldReferenceOperation: C C.field (OperationKind.FieldReference, Type: C) (Syntax: 'prop.field') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'prop.field') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: C, NarrowedType: C) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(4,7): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // C field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null").WithLocation(4, 7) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_RecursivePatternWithNestedPropertyPatterns_ControlFlow() { string source = @" class C { C field; C prop { get; } void M() /*<bind>*/ { if (this is { prop.field: null }) { } }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B2] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'this is { p ... eld: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ prop.field: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'prop') Member: IPropertyReferenceOperation: C C.prop { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'prop') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'prop') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'prop') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'prop.field') Member: IFieldReferenceOperation: C C.field (OperationKind.FieldReference, Type: C) (Syntax: 'prop.field') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'prop.field') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: C, NarrowedType: C) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1*2] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(4,7): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // C field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null").WithLocation(4, 7) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_RecursivePatternWithNestedPropertyPatterns_MissingMember() { string source = @" class C { void M() { if (/*<bind>*/this is { prop.field: null } y/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { p ... d: null } y') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ prop.field: null } y') (InputType: C, NarrowedType: C, DeclaredSymbol: C y, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'prop') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'prop') Children(0) Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'prop') (InputType: ?, NarrowedType: ?, DeclaredSymbol: null, MatchedType: ?, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'prop.field') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'prop.field') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,33): error CS0117: 'C' does not contain a definition for 'prop' // if (/*<bind>*/this is { prop.field: null } y/*</bind>*/) { } Diagnostic(ErrorCode.ERR_NoSuchMember, "prop").WithArguments("C", "prop").WithLocation(6, 33) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_RecursivePatternWithNestedPropertyPatterns_EventMember() { string source = @" class C { C prop { get; } public event System.Action action; void M() { if (/*<bind>*/this is { prop.action: null } y/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { p ... n: null } y') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ prop.action: null } y') (InputType: C, NarrowedType: C, DeclaredSymbol: C y, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'prop') Member: IPropertyReferenceOperation: C C.prop { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'prop') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'prop') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'prop') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'prop.action') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'prop.action') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(5,32): warning CS0067: The event 'C.action' is never used // public event System.Action action; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "action").WithArguments("C.action").WithLocation(5, 32), // file.cs(8,38): error CS0154: The property or indexer 'action' cannot be used in this context because it lacks the get accessor // if (/*<bind>*/this is { prop.action: null } y/*</bind>*/) { } Diagnostic(ErrorCode.ERR_PropertyLacksGet, "action").WithArguments("action").WithLocation(8, 38) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_01() { string source = @" class C { void M((int X, int Y) tuple, bool b) { if (/*<bind>*/tuple is (1, 2) { NotFound: int x } y/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'tuple is (1 ... : int x } y') Value: IParameterReferenceOperation: tuple (OperationKind.ParameterReference, Type: (System.Int32 X, System.Int32 Y)) (Syntax: 'tuple') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '(1, 2) { No ... : int x } y') (InputType: (System.Int32 X, System.Int32 Y), NarrowedType: (System.Int32 X, System.Int32 Y), DeclaredSymbol: (System.Int32 X, System.Int32 Y) y, MatchedType: (System.Int32 X, System.Int32 Y), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '2') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'NotFound: int x') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'NotFound') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: ?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) "; var expectedDiagnostics = new[] { // file.cs(6,41): error CS0117: '(int X, int Y)' does not contain a definition for 'NotFound' // if (/*<bind>*/tuple is (1, 2) { NotFound: int x } y/*</bind>*/) { } Diagnostic(ErrorCode.ERR_NoSuchMember, "NotFound").WithArguments("(int X, int Y)", "NotFound").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_02() { var vbSource = @" Public Class C1 Public Property Prop(index As Integer) As Integer Get Return 1 End Get Set End Set End Property End Class "; var vbCompilation = CreateVisualBasicCompilation(vbSource); var source = @" class C { void M1(object o, bool b) { b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; } }"; var compilation = CreateCompilation(source, new[] { vbCompilation.EmitToImageReference() }, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (6,33): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Prop[1]").WithArguments("type pattern", "9.0").WithLocation(6, 33), // (6,33): error CS8503: A property subpattern requires a reference to the property or field to be matched, e.g. '{ Name: Prop[1] }' // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyPatternNameMissing, "Prop[1]").WithArguments("Prop[1]").WithLocation(6, 33), // (6,33): error CS0246: The type or namespace name 'Prop' could not be found (are you missing a using directive or an assembly reference?) // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Prop").WithArguments("Prop").WithLocation(6, 33), // (6,37): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[1]").WithLocation(6, 37), // (6,40): error CS1003: Syntax error, ',' expected // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(6, 40), // (6,42): error CS1003: Syntax error, ',' expected // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_SyntaxError, "var").WithArguments(",", "").WithLocation(6, 42)); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is C1 { P ... 1]: var x }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'C1 { Prop[1]: var x }') (InputType: System.Object, NarrowedType: C1, DeclaredSymbol: null, MatchedType: C1, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'Prop[1]') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'Prop[1]') Children(0) Pattern: ITypePatternOperation (OperationKind.TypePattern, Type: null, IsInvalid) (Syntax: 'Prop[1]') (InputType: ?, NarrowedType: Prop[], MatchedType: Prop[]) IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'var x') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'var x') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'var x') (InputType: ?, NarrowedType: ?, DeclaredSymbol: ?? x, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_03() { var vbSource = @" Public Class C1 Public Property Prop(index As Integer) As Integer Get Return 1 End Get Set End Set End Property End Class "; var vbCompilation = CreateVisualBasicCompilation(vbSource); var source = @" class C { void M1(object o, bool b) { b = /*<bind>*/o is C1 { Prop: var x }/*</bind>*/; } }"; var compilation = CreateCompilation(source, new[] { vbCompilation.EmitToImageReference() }); compilation.VerifyDiagnostics( // (6,33): error CS0154: The property or indexer 'Prop' cannot be used in this context because it lacks the get accessor // b = /*<bind>*/o is C1 { Prop: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Prop").WithArguments("Prop").WithLocation(6, 33)); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is C1 { Prop: var x }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'C1 { Prop: var x }') (InputType: System.Object, NarrowedType: C1, DeclaredSymbol: null, MatchedType: C1, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'Prop: var x') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Prop') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var x') (InputType: ?, NarrowedType: ?, DeclaredSymbol: ?? x, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_04() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { A: var a }/*</bind>*/; } } class D { public event System.Action A; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0154: The property or indexer 'A' cannot be used in this context because it lacks the get accessor // _ = /*<bind>*/o is D { A: var a }/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "A").WithArguments("A").WithLocation(6, 32), // (11,32): warning CS0067: The event 'D.A' is never used // public event System.Action A; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "A").WithArguments("D.A").WithLocation(11, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { A: var a }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { A: var a }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'A: var a') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'A') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var a') (InputType: ?, NarrowedType: ?, DeclaredSymbol: ?? a, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_05() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { B: var b }/*</bind>*/; } } class D { public void B() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0154: The property or indexer 'B' cannot be used in this context because it lacks the get accessor // _ = /*<bind>*/o is D { B: var b }/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "B").WithArguments("B").WithLocation(6, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { B: var b }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { B: var b }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'B: var b') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'B') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var b') (InputType: ?, NarrowedType: ?, DeclaredSymbol: ?? b, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_06() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { C: var c }/*</bind>*/; } } class D { public class C { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0572: 'C': cannot reference a type through an expression; try 'D.C' instead // _ = /*<bind>*/o is D { C: var c }/*</bind>*/; Diagnostic(ErrorCode.ERR_BadTypeReference, "C").WithArguments("C", "D.C").WithLocation(6, 32), // (6,32): error CS0154: The property or indexer 'C' cannot be used in this context because it lacks the get accessor // _ = /*<bind>*/o is D { C: var c }/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "C").WithArguments("C").WithLocation(6, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { C: var c }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { C: var c }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'C: var c') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'C') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var c') (InputType: ?, NarrowedType: ?, DeclaredSymbol: ?? c, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_07() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { X: var x }/*</bind>*/; } } class D { public const int X = 3; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0176: Member 'D.X' cannot be accessed with an instance reference; qualify it with a type name instead // _ = /*<bind>*/o is D { X: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("D.X").WithLocation(6, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { X: var x }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { X: var x }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'X: var x') Member: IFieldReferenceOperation: System.Int32 D.X (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: 'X') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var x') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_08() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { X: var x }/*</bind>*/; } } class D { public static int X = 3; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0176: Member 'D.X' cannot be accessed with an instance reference; qualify it with a type name instead // _ = /*<bind>*/o is D { X: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("D.X").WithLocation(6, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { X: var x }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { X: var x }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'X: var x') Member: IFieldReferenceOperation: System.Int32 D.X (Static) (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'X') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var x') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_09() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { X: var x }/*</bind>*/; } } class D { public static int X => 3; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0176: Member 'D.X' cannot be accessed with an instance reference; qualify it with a type name instead // _ = /*<bind>*/o is D { X: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("D.X").WithLocation(6, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { X: var x }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { X: var x }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'X: var x') Member: IPropertyReferenceOperation: System.Int32 D.X { get; } (Static) (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'X') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var x') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_ControlFlowInPattern() { string source = @" class C { void M(int? x, bool b) /*<bind>*/ { b = x is (true ? 1 : 0); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block [UnReachable] Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = x is (true ? 1 : 0);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = x is (true ? 1 : 0)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is (true ? 1 : 0)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '(true ? 1 : 0)') (InputType: System.Int32?, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'true ? 1 : 0') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_ControlFlowInPattern_02() { string source = @" class C { void M((int, int) x, bool b) /*<bind>*/ { b = x is ((true ? 1 : 2), (false ? 3 : 4)); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, System.Int32)) (Syntax: 'x') Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block [UnReachable] Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Block[B5] - Block [UnReachable] Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = x is (( ... ? 3 : 4));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = x is (( ... e ? 3 : 4))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is ((true ... e ? 3 : 4))') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'x') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '((true ? 1 ... e ? 3 : 4))') (InputType: (System.Int32, System.Int32), NarrowedType: (System.Int32, System.Int32), DeclaredSymbol: null, MatchedType: (System.Int32, System.Int32), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '(true ? 1 : 2)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'true ? 1 : 2') IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '(false ? 3 : 4)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: 'false ? 3 : 4') PropertySubpatterns (0) Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_ControlFlowInValueAndPattern() { string source = @" class C { void M(int? x1, int x2, bool b) /*<bind>*/ { b = (x1 ?? x2) is (true ? 1 : 0); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'x1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B8] Block[B7] - Block [UnReachable] Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = (x1 ?? ... e ? 1 : 0);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = (x1 ?? ... ue ? 1 : 0)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '(x1 ?? x2) ... ue ? 1 : 0)') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x1 ?? x2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '(true ? 1 : 0)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'true ? 1 : 0') Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_PatternCombinatorsAndRelationalPatterns_01() { string source = @" class X { void M(char c) { _ = /*<bind>*/c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z')/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'c is (>= 'A ... and <= 'z')') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'c') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... and <= 'z')') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and <= 'Z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'A'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: A) (Syntax: ''A'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'Z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: Z) (Syntax: ''Z'') RightPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'a' and <= 'z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'a'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: z) (Syntax: ''z'') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_TypePatterns_01() { string source = @" class X { void M(object o) { _ = /*<bind>*/o is int or long or bool/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is int or long or bool') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long or bool') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'int') (InputType: System.Object, NarrowedType: System.Int32, MatchedType: System.Int32) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'long') (InputType: System.Object, NarrowedType: System.Int64, MatchedType: System.Int64) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'bool') (InputType: System.Object, NarrowedType: System.Boolean, MatchedType: System.Boolean) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_Array_01() { string source = @" class X { void M(int[] o) { _ = /*<bind>*/o is [42, ..]/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is [42, ..]') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'o') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[42, ..]') (InputType: System.Int32[], NarrowedType: System.Int32[], DeclaredSymbol: null, LengthSymbol: System.Int32 System.Array.Length { get; }, IndexerSymbol: null) Patterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '42') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ISlicePatternOperation (OperationKind.SlicePattern, Type: null) (Syntax: '..') (InputType: System.Int32[], NarrowedType: System.Int32[], SliceSymbol: null Pattern: null "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithIndex(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_Array_02() { string source = @" class X { void M(int[] o) { _ = /*<bind>*/o is [42, .. var slice] list/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is [42, . ... slice] list') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'o') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[42, .. var slice] list') (InputType: System.Int32[], NarrowedType: System.Int32[], DeclaredSymbol: System.Int32[] list, LengthSymbol: System.Int32 System.Array.Length { get; }, IndexerSymbol: null) Patterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '42') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ISlicePatternOperation (OperationKind.SlicePattern, Type: null) (Syntax: '.. var slice') (InputType: System.Int32[], NarrowedType: System.Int32[], SliceSymbol: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var slice') (InputType: System.Int32[], NarrowedType: System.Int32[], DeclaredSymbol: System.Int32[]? slice, MatchesNull: True) "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithIndexAndRange(new[] { source, TestSources.GetSubArray }); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_Array_Nullability() { string source = @" #nullable enable class X { void M(string s) { s = null; var a = new[] { s }; _ = /*<bind>*/a is [var item]/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is [var item]') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.String?[]) (Syntax: 'a') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[var item]') (InputType: System.String[], NarrowedType: System.String[], DeclaredSymbol: null, LengthSymbol: System.Int32 System.Array.Length { get; }, IndexerSymbol: null) Patterns (1): IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var item') (InputType: System.String, NarrowedType: System.String, DeclaredSymbol: System.String? item, MatchesNull: True) "; var expectedDiagnostics = new[] { // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 13) }; var comp = CreateCompilationWithIndexAndRange(new[] { source, TestSources.GetSubArray }); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(57884, "https://github.com/dotnet/roslyn/issues/57884")] public void TestIsPatternExpression_ListPatterns_Collection_Nullability() { string source = @" #nullable enable class X<T> { static X<U> Create<U>(U u) => throw null!; void M(string s) { s = null; var a = Create(s); _ = /*<bind>*/a is [var item]/*</bind>*/; } public int Length => throw null!; public char this[int i] => throw null!; } "; // The LengthSymbol and IndexerSymbol should reflect updated nullability: // LengthSymbol: System.Int32 X<System.String?>.Length { get; }, IndexerSymbol: System.Char X<System.String?>.this[System.Int32 i] { get; }) // Tracked by https://github.com/dotnet/roslyn/issues/57884 string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is [var item]') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: X<System.String?>) (Syntax: 'a') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[var item]') (InputType: X<System.String>, NarrowedType: X<System.String>, DeclaredSymbol: null, LengthSymbol: System.Int32 X<System.String>.Length { get; }, IndexerSymbol: System.Char X<System.String>.this[System.Int32 i] { get; }) Patterns (1): IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var item') (InputType: System.Char, NarrowedType: System.Char, DeclaredSymbol: System.Char item, MatchesNull: True) "; var expectedDiagnostics = new[] { // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 13) }; var comp = CreateCompilationWithIndexAndRange(new[] { source, TestSources.GetSubArray }); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_Span_01() { string source = @" class X { void M(System.Span<int> o) { _ = /*<bind>*/o is [.., 42]/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is [.., 42]') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Span<System.Int32>) (Syntax: 'o') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[.., 42]') (InputType: System.Span<System.Int32>, NarrowedType: System.Span<System.Int32>, DeclaredSymbol: null, LengthSymbol: System.Int32 System.Span<System.Int32>.Length { get; }, IndexerSymbol: ref System.Int32 System.Span<System.Int32>.this[System.Int32 i] { get; }) Patterns (2): ISlicePatternOperation (OperationKind.SlicePattern, Type: null) (Syntax: '..') (InputType: System.Span<System.Int32>, NarrowedType: System.Span<System.Int32>, SliceSymbol: null Pattern: null IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '42') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithIndexAndRangeAndSpan(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_Span_02() { string source = @" class X { void M(System.Span<int> o) { _ = /*<bind>*/o is [.. var slice, 42] list/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is [.. va ... e, 42] list') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Span<System.Int32>) (Syntax: 'o') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[.. var slice, 42] list') (InputType: System.Span<System.Int32>, NarrowedType: System.Span<System.Int32>, DeclaredSymbol: System.Span<System.Int32> list, LengthSymbol: System.Int32 System.Span<System.Int32>.Length { get; }, IndexerSymbol: ref System.Int32 System.Span<System.Int32>.this[System.Int32 i] { get; }) Patterns (2): ISlicePatternOperation (OperationKind.SlicePattern, Type: null) (Syntax: '.. var slice') (InputType: System.Span<System.Int32>, NarrowedType: System.Span<System.Int32>, SliceSymbol: System.Span<System.Int32> System.Span<System.Int32>.Slice(System.Int32 offset, System.Int32 length) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var slice') (InputType: System.Span<System.Int32>, NarrowedType: System.Span<System.Int32>, DeclaredSymbol: System.Span<System.Int32> slice, MatchesNull: True) IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '42') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithIndexAndRangeAndSpan(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_MissingMember_Length() { string source = @" class X { public int this[int i] => throw null; void M() { _ = /*<bind>*/this is []/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is []') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: X) (Syntax: 'this') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null, IsInvalid) (Syntax: '[]') (InputType: X, NarrowedType: X, DeclaredSymbol: null, LengthSymbol: null, IndexerSymbol: System.Int32 X.this[System.Int32 i] { get; }) Patterns (0) "; var expectedDiagnostics = new[] { // (8,31): error CS0518: Predefined type 'System.Index' is not defined or imported // _ = /*<bind>*/this is []/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "[]").WithArguments("System.Index").WithLocation(8, 31) }; var comp = CreateCompilation(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_MissingMember_Indexer() { string source = @" class X { public int Count { get; } void M() { _ = /*<bind>*/this is []/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is []') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: X) (Syntax: 'this') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null, IsInvalid) (Syntax: '[]') (InputType: X, NarrowedType: X, DeclaredSymbol: null, LengthSymbol: System.Int32 X.Count { get; }, IndexerSymbol: null) Patterns (0) "; var expectedDiagnostics = new[] { // (8,31): error CS0021: Cannot apply indexing with [] to an expression of type 'X' // _ = /*<bind>*/this is []/*</bind>*/; Diagnostic(ErrorCode.ERR_BadIndexLHS, "[]").WithArguments("X").WithLocation(8, 31) }; var comp = CreateCompilationWithIndex(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_MissingMember_Slice() { string source = @" class X { public int this[int i] => throw null; public int Count => throw null; void M() { _ = /*<bind>*/this is [.. 0]/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is [.. 0]') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: X) (Syntax: 'this') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null, IsInvalid) (Syntax: '[.. 0]') (InputType: X, NarrowedType: X, DeclaredSymbol: null, LengthSymbol: System.Int32 X.Count { get; }, IndexerSymbol: System.Int32 X.this[System.Int32 i] { get; }) Patterns (1): ISlicePatternOperation (OperationKind.SlicePattern, Type: null, IsInvalid) (Syntax: '.. 0') (InputType: X, NarrowedType: X, SliceSymbol: System.Int32 X.this[System.Int32 i] { get; } Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '0') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') "; var expectedDiagnostics = new[] { // (9,32): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int' // _ = /*<bind>*/this is [.. 0]/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, ".. 0").WithArguments("1", "System.Range", "int").WithLocation(9, 32) }; var comp = CreateCompilationWithIndexAndRange(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_ErrorCases_01() { string source = @" class X { void M(int[] a) { _ = /*<bind>*/a is ../*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'a is ..') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Pattern: ISlicePatternOperation (OperationKind.SlicePattern, Type: null, IsInvalid) (Syntax: '..') (InputType: System.Int32[], NarrowedType: System.Int32[], SliceSymbol: null Pattern: null "; var expectedDiagnostics = new[] { // (6,28): error CS9202: Slice patterns may only be used once and directly inside a list pattern. // _ = /*<bind>*/a is ../*</bind>*/; Diagnostic(ErrorCode.ERR_MisplacedSlicePattern, "..").WithLocation(6, 28) }; var comp = CreateCompilation(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_ErrorCases_02() { string source = @" class X { void M(int[] a) { _ = /*<bind>*/a is .. 42/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'a is .. 42') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Pattern: ISlicePatternOperation (OperationKind.SlicePattern, Type: null, IsInvalid) (Syntax: '.. 42') (InputType: System.Int32[], NarrowedType: System.Int32[], SliceSymbol: null Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '42') (InputType: System.Int32[], NarrowedType: System.Int32[]) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[], IsInvalid, IsImplicit) (Syntax: '42') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new[] { // (6,28): error CS9202: Slice patterns may only be used once and directly inside a list pattern. // _ = /*<bind>*/a is .. 42/*</bind>*/; Diagnostic(ErrorCode.ERR_MisplacedSlicePattern, ".. 42").WithLocation(6, 28), // (6,31): error CS0029: Cannot implicitly convert type 'int' to 'int[]' // _ = /*<bind>*/a is .. 42/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "42").WithArguments("int", "int[]").WithLocation(6, 31) }; var comp = CreateCompilation(new[] { source, TestSources.Index, TestSources.Range, TestSources.GetSubArray }); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_ControlFlow_01() { string source = @" class C { void M(int[] o) /*<bind>*/ { if (o is [1, .. var slice, 2]) { } }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32[]? slice] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B2] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is [1, .. ... r slice, 2]') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'o') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[1, .. var slice, 2]') (InputType: System.Int32[], NarrowedType: System.Int32[], DeclaredSymbol: null, LengthSymbol: System.Int32 System.Array.Length { get; }, IndexerSymbol: null) Patterns (3): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISlicePatternOperation (OperationKind.SlicePattern, Type: null) (Syntax: '.. var slice') (InputType: System.Int32[], NarrowedType: System.Int32[], SliceSymbol: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var slice') (InputType: System.Int32[], NarrowedType: System.Int32[], DeclaredSymbol: System.Int32[]? slice, MatchesNull: True) IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '2') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Leaving: {R1} Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1*2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(new[] { source, TestSources.Index, TestSources.Range, TestSources.GetSubArray }, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); } } }
// 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IIsPatternExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_VarPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; if (/*<bind>*/x is var y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is var y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32?, NarrowedType: System.Int32?, DeclaredSymbol: System.Int32? y, MatchesNull: True) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_PrimitiveTypePatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; if (/*<bind>*/x is int y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is int y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_ReferenceTypePatternDeclaration() { string source = @" using System; class X { void M(X x) { if (/*<bind>*/x is X y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is X y') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: X) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: X, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_TypeParameterTypePatternDeclaration() { string source = @" using System; class X { void M<T>(T x) where T: class { if (/*<bind>*/x is T y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is T y') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: T) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'T y') (InputType: T, NarrowedType: T, DeclaredSymbol: T y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_DynamicTypePatternDeclaration() { string source = @" using System; class X { void M(X x) { if (/*<bind>*/x is dynamic y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is dynamic y') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: X) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'dynamic y') (InputType: X, NarrowedType: dynamic, DeclaredSymbol: dynamic y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS8208: It is not legal to use the type 'dynamic' in a pattern. // if (/*<bind>*/x is dynamic y/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_PatternDynamicType, "dynamic").WithLocation(7, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_ConstantPattern() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is 12/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is 12') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '12') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_ConstantPatternWithConversion() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is (int)12.0/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is (int)12.0') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '(int)12.0') (InputType: System.Int32?, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 12) (Syntax: '(int)12.0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 12) (Syntax: '12.0') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_ConstantPatternWithNoImplicitConversion() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is 12.0/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is 12.0') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '12.0') (InputType: System.Int32?, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 12, IsInvalid, IsImplicit) (Syntax: '12.0') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 12, IsInvalid) (Syntax: '12.0') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0266: Cannot implicitly convert type 'double' to 'int?'. An explicit conversion exists (are you missing a cast?) // if (/*<bind>*/x is 12.0/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "12.0").WithArguments("double", "int?").WithLocation(8, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_ConstantPatternWithNoValidImplicitOrExplicitConversion() { string source = @" using System; class X { void M() { int x = 12, y = 12; if (/*<bind>*/x is null/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is null') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: 'null') (InputType: System.Int32, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0037: Cannot convert null to 'int' because it is a non-nullable value type // if (/*<bind>*/x is null/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_UndefinedTypeInPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; if (/*<bind>*/x is UndefinedType y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is UndefinedType y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'UndefinedType y') (InputType: System.Int32?, NarrowedType: UndefinedType, DeclaredSymbol: UndefinedType y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) // if (/*<bind>*/x is UndefinedType y/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndefinedType").WithArguments("UndefinedType").WithLocation(8, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidConstantPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'y') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32?, IsInvalid) (Syntax: 'y') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0150: A constant value is expected // if (/*<bind>*/x is y/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_ConstantExpected, "y").WithLocation(8, 28) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidTypeInPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; if (/*<bind>*/x is X y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is X y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'X y') (InputType: System.Int32?, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS8121: An expression of type 'int?' cannot be handled by a pattern of type 'X'. // if (/*<bind>*/x is X y/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_PatternWrongType, "X").WithArguments("int?", "X").WithLocation(8, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_DuplicateLocalInPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is int y/*</bind>*/) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is int y') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int y') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0128: A local variable or function named 'y' is already defined in this scope // if (/*<bind>*/x is int y/*</bind>*/) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_LocalDuplicate, "y").WithArguments("y").WithLocation(8, 32) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidMultipleLocalsInPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12, y = 12; if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is int y2') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y2') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y2, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1026: ) expected // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_CloseParenExpected, ",").WithLocation(8, 45), // CS1525: Invalid expression term ',' // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(8, 45), // CS1002: ; expected // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_SemicolonExpected, ",").WithLocation(8, 45), // CS1513: } expected // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_RbraceExpected, ",").WithLocation(8, 45), // CS1002: ; expected // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 49), // CS1513: } expected // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 49), // CS0103: The name 'y3' does not exist in the current context // if (/*<bind>*/x is int y2/*</bind>*/, y3) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_NameNotInContext, "y3").WithArguments("y3").WithLocation(8, 47) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidConstDeclarationInPatternDeclaration() { string source = @" using System; class X { void M() { int x = 12; if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean, IsInvalid) (Syntax: 'x is /*</bind>*/') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') IsType: ? "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,39): error CS1525: Invalid expression term 'const' // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "const").WithArguments("const").WithLocation(8, 39), // file.cs(8,39): error CS1026: ) expected // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_CloseParenExpected, "const").WithLocation(8, 39), // file.cs(8,49): error CS0145: A const field requires a value to be provided // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_ConstValueRequired, "y").WithLocation(8, 49), // file.cs(8,50): error CS1002: ; expected // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 50), // file.cs(8,50): error CS1513: } expected // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 50), // file.cs(8,39): error CS1023: Embedded statement cannot be a declaration or labeled statement // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "const int y").WithLocation(8, 39), // file.cs(8,70): error CS0103: The name 'y' does not exist in the current context // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(8, 70), // file.cs(8,49): warning CS0168: The variable 'y' is declared but never used // if (/*<bind>*/x is /*</bind>*/const int y) Console.WriteLine(y); Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(8, 49) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidInDefaultParameterInitializer() { string source = @" using System; class X { void M(string x = /*<bind>*/string.Empty is string y/*</bind>*/) { } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'string.Empty is string y') Value: IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'string y') (InputType: System.String, NarrowedType: System.String, DeclaredSymbol: System.String y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1736: Default parameter value for 'x' must be a compile-time constant // void M(string x = /*<bind>*/string.Empty is string y/*</bind>*/) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "string.Empty is string y").WithArguments("x").WithLocation(5, 33) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidInFieldInitializer() { string source = @" class C { private readonly static object o = 1; private readonly bool b = /*<bind>*/o is int x/*</bind>*/ && x >= 5; } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is int x') Value: IFieldReferenceOperation: System.Object C.o (Static) (OperationKind.FieldReference, Type: System.Object) (Syntax: 'o') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidInConstructorInitializer() { string source = @" class C { public C(object o): this (/*<bind>*/o is int x/*</bind>*/ && x >= 5) { } public C (bool b) { } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is int x') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestIsPatternExpression_InvalidInAttributeArgument() { string source = @" class A: System.Attribute { public A (bool i) { } } [A(/*<bind>*/o is int x/*</bind>*/ && x >= 5)] class C { private const object o = 1; } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is int x') Value: IFieldReferenceOperation: System.Object C.o (Static) (OperationKind.FieldReference, Type: System.Object, Constant: 1, IsInvalid) (Syntax: 'o') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0134: 'C.o' is of type 'object'. A const field of a reference type other than string can only be initialized with null. // private const object o = 1; Diagnostic(ErrorCode.ERR_NotNullConstRefField, "1").WithArguments("C.o", "object").WithLocation(12, 30), // CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(/*<bind>*/o is int x/*</bind>*/ && x >= 5)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "o is int x/*</bind>*/ && x >= 5").WithLocation(9, 14) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_NoControlFlow_01() { string source = @" class C { void M(int? x, bool b, int x2, bool b2) /*<bind>*/{ b = x is var y; b2 = x2 is 1; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32? y] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = x is var y;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = x is var y') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is var y') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32?, NarrowedType: System.Int32?, DeclaredSymbol: System.Int32? y, MatchesNull: True) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b2 = x2 is 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b2 = x2 is 1') Left: IParameterReferenceOperation: b2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b2') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x2 is 1') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_NoControlFlow_02() { string source = @" class C { void M((int X, int Y)? x, bool b) /*<bind>*/{ b = x is (1, _) { Item1: var z } p; }/*</bind>*/ } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedOperationTree = @" IBlockOperation (1 statements, 2 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: (System.Int32 X, System.Int32 Y) p Local_2: System.Int32 z IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = x is (1 ... var z } p;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = x is (1 ... : var z } p') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is (1, _) ... : var z } p') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32 X, System.Int32 Y)?) (Syntax: 'x') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(1, _) { It ... : var z } p') (InputType: (System.Int32 X, System.Int32 Y)?, NarrowedType: (System.Int32 X, System.Int32 Y), DeclaredSymbol: (System.Int32 X, System.Int32 Y) p, MatchedType: (System.Int32 X, System.Int32 Y), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Item1: var z') Member: IFieldReferenceOperation: System.Int32 (System.Int32 X, System.Int32 Y).Item1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Item1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 X, System.Int32 Y), IsImplicit) (Syntax: 'Item1') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: True) "; VerifyOperationTreeForTest<BlockSyntax>(compilation, expectedOperationTree); string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [(System.Int32 X, System.Int32 Y) p] [System.Int32 z] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = x is (1 ... var z } p;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = x is (1 ... : var z } p') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is (1, _) ... : var z } p') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32 X, System.Int32 Y)?) (Syntax: 'x') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(1, _) { It ... : var z } p') (InputType: (System.Int32 X, System.Int32 Y)?, NarrowedType: (System.Int32 X, System.Int32 Y), DeclaredSymbol: (System.Int32 X, System.Int32 Y) p, MatchedType: (System.Int32 X, System.Int32 Y), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Item1: var z') Member: IFieldReferenceOperation: System.Int32 (System.Int32 X, System.Int32 Y).Item1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Item1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 X, System.Int32 Y), IsImplicit) (Syntax: 'Item1') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: True) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0)"; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedFlowGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_NoControlFlow_03() { string source = @" class C { void M((int X, (int Y, int Z))? tuple, bool b) /*<bind>*/{ b = tuple is (1, _) { Item1: var x, Item2: { Y: 1, Z: var z } } p; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [(System.Int32 X, (System.Int32 Y, System.Int32 Z)) p] [System.Int32 x] [System.Int32 z] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = tuple i ... ar z } } p;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = tuple i ... var z } } p') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'tuple is (1 ... var z } } p') Value: IParameterReferenceOperation: tuple (OperationKind.ParameterReference, Type: (System.Int32 X, (System.Int32 Y, System.Int32 Z))?) (Syntax: 'tuple') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(1, _) { It ... var z } } p') (InputType: (System.Int32 X, (System.Int32 Y, System.Int32 Z))?, NarrowedType: (System.Int32 X, (System.Int32 Y, System.Int32 Z)), DeclaredSymbol: (System.Int32 X, (System.Int32 Y, System.Int32 Z)) p, MatchedType: (System.Int32 X, (System.Int32 Y, System.Int32 Z)), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: (System.Int32 Y, System.Int32 Z), NarrowedType: (System.Int32 Y, System.Int32 Z)) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Item1: var x') Member: IFieldReferenceOperation: System.Int32 (System.Int32 X, (System.Int32 Y, System.Int32 Z)).Item1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Item1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 X, (System.Int32 Y, System.Int32 Z)), IsImplicit) (Syntax: 'Item1') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var x') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: True) IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Item2: { Y: ... Z: var z }') Member: IFieldReferenceOperation: (System.Int32 Y, System.Int32 Z) (System.Int32 X, (System.Int32 Y, System.Int32 Z)).Item2 (OperationKind.FieldReference, Type: (System.Int32 Y, System.Int32 Z)) (Syntax: 'Item2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 X, (System.Int32 Y, System.Int32 Z)), IsImplicit) (Syntax: 'Item2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ Y: 1, Z: var z }') (InputType: (System.Int32 Y, System.Int32 Z), NarrowedType: (System.Int32 Y, System.Int32 Z), DeclaredSymbol: null, MatchedType: (System.Int32 Y, System.Int32 Z), DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Y: 1') Member: IFieldReferenceOperation: System.Int32 (System.Int32 Y, System.Int32 Z).Y (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 Y, System.Int32 Z), IsImplicit) (Syntax: 'Y') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Z: var z') Member: IFieldReferenceOperation: System.Int32 (System.Int32 Y, System.Int32 Z).Z (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Z') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 Y, System.Int32 Z), IsImplicit) (Syntax: 'Z') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var z') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: True) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_ControlFlowInValue() { string source = @" class C { void M(int? x1, int x2, bool b) /*<bind>*/{ b = (x1 ?? x2) is var y; }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 y] CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'x1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = (x1 ?? x2) is var y;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = (x1 ?? x2) is var y') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '(x1 ?? x2) is var y') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x1 ?? x2') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: True) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_RecursivePattern() { string source = @" class C { void M((int X, int Y) tuple, bool b) { if (/*<bind>*/tuple is (1, 2) { Item1: int x } y/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'tuple is (1 ... : int x } y') Value: IParameterReferenceOperation: tuple (OperationKind.ParameterReference, Type: (System.Int32 X, System.Int32 Y)) (Syntax: 'tuple') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(1, 2) { It ... : int x } y') (InputType: (System.Int32 X, System.Int32 Y), NarrowedType: (System.Int32 X, System.Int32 Y), DeclaredSymbol: (System.Int32 X, System.Int32 Y) y, MatchedType: (System.Int32 X, System.Int32 Y), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '2') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null) (Syntax: 'Item1: int x') Member: IFieldReferenceOperation: System.Int32 (System.Int32 X, System.Int32 Y).Item1 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'Item1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: (System.Int32 X, System.Int32 Y), IsImplicit) (Syntax: 'Item1') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_RecursivePatternWithNestedPropertyPatterns() { string source = @" class C { C field; C prop { get; } void M() { if (/*<bind>*/this is { prop.field: null }/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'this is { p ... eld: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ prop.field: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'prop') Member: IPropertyReferenceOperation: C C.prop { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'prop') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'prop') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'prop') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'prop.field') Member: IFieldReferenceOperation: C C.field (OperationKind.FieldReference, Type: C) (Syntax: 'prop.field') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'prop.field') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: C, NarrowedType: C) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(4,7): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // C field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null").WithLocation(4, 7) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_RecursivePatternWithNestedPropertyPatterns_ControlFlow() { string source = @" class C { C field; C prop { get; } void M() /*<bind>*/ { if (this is { prop.field: null }) { } }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B2] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'this is { p ... eld: null }') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '{ prop.field: null }') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'prop') Member: IPropertyReferenceOperation: C C.prop { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'prop') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'prop') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'prop') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'prop.field') Member: IFieldReferenceOperation: C C.field (OperationKind.FieldReference, Type: C) (Syntax: 'prop.field') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'prop.field') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: C, NarrowedType: C) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1*2] Statements (0) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(4,7): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // C field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null").WithLocation(4, 7) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_RecursivePatternWithNestedPropertyPatterns_MissingMember() { string source = @" class C { void M() { if (/*<bind>*/this is { prop.field: null } y/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { p ... d: null } y') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ prop.field: null } y') (InputType: C, NarrowedType: C, DeclaredSymbol: C y, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'prop') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'prop') Children(0) Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'prop') (InputType: ?, NarrowedType: ?, DeclaredSymbol: null, MatchedType: ?, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'prop.field') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'prop.field') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,33): error CS0117: 'C' does not contain a definition for 'prop' // if (/*<bind>*/this is { prop.field: null } y/*</bind>*/) { } Diagnostic(ErrorCode.ERR_NoSuchMember, "prop").WithArguments("C", "prop").WithLocation(6, 33) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_RecursivePatternWithNestedPropertyPatterns_EventMember() { string source = @" class C { C prop { get; } public event System.Action action; void M() { if (/*<bind>*/this is { prop.action: null } y/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is { p ... n: null } y') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '{ prop.action: null } y') (InputType: C, NarrowedType: C, DeclaredSymbol: C y, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsImplicit) (Syntax: 'prop') Member: IPropertyReferenceOperation: C C.prop { get; } (OperationKind.PropertyReference, Type: C) (Syntax: 'prop') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: PatternInput) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'prop') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsImplicit) (Syntax: 'prop') (InputType: C, NarrowedType: C, DeclaredSymbol: null, MatchedType: C, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'prop.action') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'prop.action') Children(0) Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'null') (InputType: ?, NarrowedType: ?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(5,32): warning CS0067: The event 'C.action' is never used // public event System.Action action; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "action").WithArguments("C.action").WithLocation(5, 32), // file.cs(8,38): error CS0154: The property or indexer 'action' cannot be used in this context because it lacks the get accessor // if (/*<bind>*/this is { prop.action: null } y/*</bind>*/) { } Diagnostic(ErrorCode.ERR_PropertyLacksGet, "action").WithArguments("action").WithLocation(8, 38) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_01() { string source = @" class C { void M((int X, int Y) tuple, bool b) { if (/*<bind>*/tuple is (1, 2) { NotFound: int x } y/*</bind>*/) { } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'tuple is (1 ... : int x } y') Value: IParameterReferenceOperation: tuple (OperationKind.ParameterReference, Type: (System.Int32 X, System.Int32 Y)) (Syntax: 'tuple') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: '(1, 2) { No ... : int x } y') (InputType: (System.Int32 X, System.Int32 Y), NarrowedType: (System.Int32 X, System.Int32 Y), DeclaredSymbol: (System.Int32 X, System.Int32 Y) y, MatchedType: (System.Int32 X, System.Int32 Y), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '2') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'NotFound: int x') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'NotFound') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: ?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) "; var expectedDiagnostics = new[] { // file.cs(6,41): error CS0117: '(int X, int Y)' does not contain a definition for 'NotFound' // if (/*<bind>*/tuple is (1, 2) { NotFound: int x } y/*</bind>*/) { } Diagnostic(ErrorCode.ERR_NoSuchMember, "NotFound").WithArguments("(int X, int Y)", "NotFound").WithLocation(6, 41) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_02() { var vbSource = @" Public Class C1 Public Property Prop(index As Integer) As Integer Get Return 1 End Get Set End Set End Property End Class "; var vbCompilation = CreateVisualBasicCompilation(vbSource); var source = @" class C { void M1(object o, bool b) { b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; } }"; var compilation = CreateCompilation(source, new[] { vbCompilation.EmitToImageReference() }, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (6,33): error CS8400: Feature 'type pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "Prop[1]").WithArguments("type pattern", "9.0").WithLocation(6, 33), // (6,33): error CS8503: A property subpattern requires a reference to the property or field to be matched, e.g. '{ Name: Prop[1] }' // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyPatternNameMissing, "Prop[1]").WithArguments("Prop[1]").WithLocation(6, 33), // (6,33): error CS0246: The type or namespace name 'Prop' could not be found (are you missing a using directive or an assembly reference?) // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Prop").WithArguments("Prop").WithLocation(6, 33), // (6,37): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[1]").WithLocation(6, 37), // (6,40): error CS1003: Syntax error, ',' expected // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(6, 40), // (6,42): error CS1003: Syntax error, ',' expected // b = /*<bind>*/o is C1 { Prop[1]: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_SyntaxError, "var").WithArguments(",", "").WithLocation(6, 42)); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is C1 { P ... 1]: var x }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'C1 { Prop[1]: var x }') (InputType: System.Object, NarrowedType: C1, DeclaredSymbol: null, MatchedType: C1, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (2): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'Prop[1]') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'Prop[1]') Children(0) Pattern: ITypePatternOperation (OperationKind.TypePattern, Type: null, IsInvalid) (Syntax: 'Prop[1]') (InputType: ?, NarrowedType: Prop[], MatchedType: Prop[]) IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'var x') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'var x') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'var x') (InputType: ?, NarrowedType: ?, DeclaredSymbol: ?? x, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_03() { var vbSource = @" Public Class C1 Public Property Prop(index As Integer) As Integer Get Return 1 End Get Set End Set End Property End Class "; var vbCompilation = CreateVisualBasicCompilation(vbSource); var source = @" class C { void M1(object o, bool b) { b = /*<bind>*/o is C1 { Prop: var x }/*</bind>*/; } }"; var compilation = CreateCompilation(source, new[] { vbCompilation.EmitToImageReference() }); compilation.VerifyDiagnostics( // (6,33): error CS0154: The property or indexer 'Prop' cannot be used in this context because it lacks the get accessor // b = /*<bind>*/o is C1 { Prop: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "Prop").WithArguments("Prop").WithLocation(6, 33)); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is C1 { Prop: var x }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'C1 { Prop: var x }') (InputType: System.Object, NarrowedType: C1, DeclaredSymbol: null, MatchedType: C1, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'Prop: var x') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'Prop') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var x') (InputType: ?, NarrowedType: ?, DeclaredSymbol: ?? x, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_04() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { A: var a }/*</bind>*/; } } class D { public event System.Action A; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0154: The property or indexer 'A' cannot be used in this context because it lacks the get accessor // _ = /*<bind>*/o is D { A: var a }/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "A").WithArguments("A").WithLocation(6, 32), // (11,32): warning CS0067: The event 'D.A' is never used // public event System.Action A; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "A").WithArguments("D.A").WithLocation(11, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { A: var a }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { A: var a }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'A: var a') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'A') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var a') (InputType: ?, NarrowedType: ?, DeclaredSymbol: ?? a, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_05() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { B: var b }/*</bind>*/; } } class D { public void B() { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0154: The property or indexer 'B' cannot be used in this context because it lacks the get accessor // _ = /*<bind>*/o is D { B: var b }/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "B").WithArguments("B").WithLocation(6, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { B: var b }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { B: var b }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'B: var b') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'B') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var b') (InputType: ?, NarrowedType: ?, DeclaredSymbol: ?? b, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_06() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { C: var c }/*</bind>*/; } } class D { public class C { } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0572: 'C': cannot reference a type through an expression; try 'D.C' instead // _ = /*<bind>*/o is D { C: var c }/*</bind>*/; Diagnostic(ErrorCode.ERR_BadTypeReference, "C").WithArguments("C", "D.C").WithLocation(6, 32), // (6,32): error CS0154: The property or indexer 'C' cannot be used in this context because it lacks the get accessor // _ = /*<bind>*/o is D { C: var c }/*</bind>*/; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "C").WithArguments("C").WithLocation(6, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { C: var c }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { C: var c }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'C: var c') Member: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'C') Children(0) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var c') (InputType: ?, NarrowedType: ?, DeclaredSymbol: ?? c, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_07() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { X: var x }/*</bind>*/; } } class D { public const int X = 3; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0176: Member 'D.X' cannot be accessed with an instance reference; qualify it with a type name instead // _ = /*<bind>*/o is D { X: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("D.X").WithLocation(6, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { X: var x }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { X: var x }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'X: var x') Member: IFieldReferenceOperation: System.Int32 D.X (Static) (OperationKind.FieldReference, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: 'X') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var x') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_08() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { X: var x }/*</bind>*/; } } class D { public static int X = 3; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0176: Member 'D.X' cannot be accessed with an instance reference; qualify it with a type name instead // _ = /*<bind>*/o is D { X: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("D.X").WithLocation(6, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { X: var x }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { X: var x }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'X: var x') Member: IFieldReferenceOperation: System.Int32 D.X (Static) (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'X') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var x') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void IsPattern_BadRecursivePattern_09() { var source = @" class C { void M1(object o) { _ = /*<bind>*/o is D { X: var x }/*</bind>*/; } } class D { public static int X => 3; } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,32): error CS0176: Member 'D.X' cannot be accessed with an instance reference; qualify it with a type name instead // _ = /*<bind>*/o is D { X: var x }/*</bind>*/; Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("D.X").WithLocation(6, 32) ); var expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o is D { X: var x }') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null, IsInvalid) (Syntax: 'D { X: var x }') (InputType: System.Object, NarrowedType: D, DeclaredSymbol: null, MatchedType: D, DeconstructSymbol: null) DeconstructionSubpatterns (0) PropertySubpatterns (1): IPropertySubpatternOperation (OperationKind.PropertySubpattern, Type: null, IsInvalid) (Syntax: 'X: var x') Member: IPropertyReferenceOperation: System.Int32 D.X { get; } (Static) (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'X') Instance Receiver: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var x') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: True) "; VerifyOperationTreeForTest<IsPatternExpressionSyntax>(compilation, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_ControlFlowInPattern() { string source = @" class C { void M(int? x, bool b) /*<bind>*/ { b = x is (true ? 1 : 0); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block [UnReachable] Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = x is (true ? 1 : 0);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = x is (true ? 1 : 0)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is (true ? 1 : 0)') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '(true ? 1 : 0)') (InputType: System.Int32?, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'true ? 1 : 0') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_ControlFlowInPattern_02() { string source = @" class C { void M((int, int) x, bool b) /*<bind>*/ { b = x is ((true ? 1 : 2), (false ? 3 : 4)); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: (System.Int32, System.Int32)) (Syntax: 'x') Jump if False (Regular) to Block[B3] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block [UnReachable] Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Block[B5] - Block [UnReachable] Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = x is (( ... ? 3 : 4));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = x is (( ... e ? 3 : 4))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is ((true ... e ? 3 : 4))') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'x') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '((true ? 1 ... e ? 3 : 4))') (InputType: (System.Int32, System.Int32), NarrowedType: (System.Int32, System.Int32), DeclaredSymbol: null, MatchedType: (System.Int32, System.Int32), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '(true ? 1 : 2)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'true ? 1 : 2') IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '(false ? 3 : 4)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: 'false ? 3 : 4') PropertySubpatterns (0) Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void IsPattern_ControlFlowInValueAndPattern() { string source = @" class C { void M(int? x1, int x2, bool b) /*<bind>*/ { b = (x1 ?? x2) is (true ? 1 : 0); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'x1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'x1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B8] Block[B7] - Block [UnReachable] Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = (x1 ?? ... e ? 1 : 0);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = (x1 ?? ... ue ? 1 : 0)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '(x1 ?? x2) ... ue ? 1 : 0)') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x1 ?? x2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '(true ? 1 : 0)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'true ? 1 : 0') Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_PatternCombinatorsAndRelationalPatterns_01() { string source = @" class X { void M(char c) { _ = /*<bind>*/c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z')/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'c is (>= 'A ... and <= 'z')') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'c') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... and <= 'z')') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and <= 'Z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'A'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: A) (Syntax: ''A'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'Z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: Z) (Syntax: ''Z'') RightPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'a' and <= 'z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'a'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: z) (Syntax: ''z'') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_TypePatterns_01() { string source = @" class X { void M(object o) { _ = /*<bind>*/o is int or long or bool/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is int or long or bool') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long or bool') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'int') (InputType: System.Object, NarrowedType: System.Int32, MatchedType: System.Int32) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'long') (InputType: System.Object, NarrowedType: System.Int64, MatchedType: System.Int64) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'bool') (InputType: System.Object, NarrowedType: System.Boolean, MatchedType: System.Boolean) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_Array_01() { string source = @" class X { void M(int[] o) { _ = /*<bind>*/o is [42, ..]/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is [42, ..]') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'o') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[42, ..]') (InputType: System.Int32[], NarrowedType: System.Int32[], DeclaredSymbol: null, LengthSymbol: System.Int32 System.Array.Length { get; }, IndexerSymbol: null) Patterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '42') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ISlicePatternOperation (OperationKind.SlicePattern, Type: null) (Syntax: '..') (InputType: System.Int32[], NarrowedType: System.Int32[], SliceSymbol: null Pattern: null "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithIndex(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_Array_02() { string source = @" class X { void M(int[] o) { _ = /*<bind>*/o is [42, .. var slice] list/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is [42, . ... slice] list') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'o') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[42, .. var slice] list') (InputType: System.Int32[], NarrowedType: System.Int32[], DeclaredSymbol: System.Int32[] list, LengthSymbol: System.Int32 System.Array.Length { get; }, IndexerSymbol: null) Patterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '42') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') ISlicePatternOperation (OperationKind.SlicePattern, Type: null) (Syntax: '.. var slice') (InputType: System.Int32[], NarrowedType: System.Int32[], SliceSymbol: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var slice') (InputType: System.Int32[], NarrowedType: System.Int32[], DeclaredSymbol: System.Int32[]? slice, MatchesNull: True) "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithIndexAndRange(new[] { source, TestSources.GetSubArray }); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_Array_Nullability() { string source = @" #nullable enable class X { void M(string s) { s = null; var a = new[] { s }; _ = /*<bind>*/a is [var item]/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is [var item]') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.String?[]) (Syntax: 'a') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[var item]') (InputType: System.String[], NarrowedType: System.String[], DeclaredSymbol: null, LengthSymbol: System.Int32 System.Array.Length { get; }, IndexerSymbol: null) Patterns (1): IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var item') (InputType: System.String, NarrowedType: System.String, DeclaredSymbol: System.String? item, MatchesNull: True) "; var expectedDiagnostics = new[] { // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 13) }; var comp = CreateCompilationWithIndexAndRange(new[] { source, TestSources.GetSubArray }); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(57884, "https://github.com/dotnet/roslyn/issues/57884")] public void TestIsPatternExpression_ListPatterns_Collection_Nullability() { string source = @" #nullable enable class X<T> { static X<U> Create<U>(U u) => throw null!; void M(string s) { s = null; var a = Create(s); _ = /*<bind>*/a is [var item]/*</bind>*/; } public int Length => throw null!; public char this[int i] => throw null!; } "; // The LengthSymbol and IndexerSymbol should reflect updated nullability: // LengthSymbol: System.Int32 X<System.String?>.Length { get; }, IndexerSymbol: System.Char X<System.String?>.this[System.Int32 i] { get; }) // Tracked by https://github.com/dotnet/roslyn/issues/57884 string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'a is [var item]') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: X<System.String?>) (Syntax: 'a') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[var item]') (InputType: X<System.String>, NarrowedType: X<System.String>, DeclaredSymbol: null, LengthSymbol: System.Int32 X<System.String>.Length { get; }, IndexerSymbol: System.Char X<System.String>.this[System.Int32 i] { get; }) Patterns (1): IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var item') (InputType: System.Char, NarrowedType: System.Char, DeclaredSymbol: System.Char item, MatchesNull: True) "; var expectedDiagnostics = new[] { // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 13) }; var comp = CreateCompilationWithIndexAndRange(new[] { source, TestSources.GetSubArray }); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_Span_01() { string source = @" class X { void M(System.Span<int> o) { _ = /*<bind>*/o is [.., 42]/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is [.., 42]') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Span<System.Int32>) (Syntax: 'o') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[.., 42]') (InputType: System.Span<System.Int32>, NarrowedType: System.Span<System.Int32>, DeclaredSymbol: null, LengthSymbol: System.Int32 System.Span<System.Int32>.Length { get; }, IndexerSymbol: ref System.Int32 System.Span<System.Int32>.this[System.Int32 i] { get; }) Patterns (2): ISlicePatternOperation (OperationKind.SlicePattern, Type: null) (Syntax: '..') (InputType: System.Span<System.Int32>, NarrowedType: System.Span<System.Int32>, SliceSymbol: null Pattern: null IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '42') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithIndexAndRangeAndSpan(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_Span_02() { string source = @" class X { void M(System.Span<int> o) { _ = /*<bind>*/o is [.. var slice, 42] list/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is [.. va ... e, 42] list') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Span<System.Int32>) (Syntax: 'o') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[.. var slice, 42] list') (InputType: System.Span<System.Int32>, NarrowedType: System.Span<System.Int32>, DeclaredSymbol: System.Span<System.Int32> list, LengthSymbol: System.Int32 System.Span<System.Int32>.Length { get; }, IndexerSymbol: ref System.Int32 System.Span<System.Int32>.this[System.Int32 i] { get; }) Patterns (2): ISlicePatternOperation (OperationKind.SlicePattern, Type: null) (Syntax: '.. var slice') (InputType: System.Span<System.Int32>, NarrowedType: System.Span<System.Int32>, SliceSymbol: System.Span<System.Int32> System.Span<System.Int32>.Slice(System.Int32 offset, System.Int32 length) Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var slice') (InputType: System.Span<System.Int32>, NarrowedType: System.Span<System.Int32>, DeclaredSymbol: System.Span<System.Int32> slice, MatchesNull: True) IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '42') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') "; var expectedDiagnostics = DiagnosticDescription.None; var comp = CreateCompilationWithIndexAndRangeAndSpan(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_MissingMember_Length() { string source = @" class X { public int this[int i] => throw null; void M() { _ = /*<bind>*/this is []/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is []') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: X) (Syntax: 'this') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null, IsInvalid) (Syntax: '[]') (InputType: X, NarrowedType: X, DeclaredSymbol: null, LengthSymbol: null, IndexerSymbol: System.Int32 X.this[System.Int32 i] { get; }) Patterns (0) "; var expectedDiagnostics = new[] { // (8,31): error CS0518: Predefined type 'System.Index' is not defined or imported // _ = /*<bind>*/this is []/*</bind>*/; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "[]").WithArguments("System.Index").WithLocation(8, 31) }; var comp = CreateCompilation(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_MissingMember_Indexer() { string source = @" class X { public int Count { get; } void M() { _ = /*<bind>*/this is []/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is []') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: X) (Syntax: 'this') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null, IsInvalid) (Syntax: '[]') (InputType: X, NarrowedType: X, DeclaredSymbol: null, LengthSymbol: System.Int32 X.Count { get; }, IndexerSymbol: null) Patterns (0) "; var expectedDiagnostics = new[] { // (8,31): error CS0021: Cannot apply indexing with [] to an expression of type 'X' // _ = /*<bind>*/this is []/*</bind>*/; Diagnostic(ErrorCode.ERR_BadIndexLHS, "[]").WithArguments("X").WithLocation(8, 31) }; var comp = CreateCompilationWithIndex(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_MissingMember_Slice() { string source = @" class X { public int this[int i] => throw null; public int Count => throw null; void M() { _ = /*<bind>*/this is [.. 0]/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'this is [.. 0]') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: X) (Syntax: 'this') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null, IsInvalid) (Syntax: '[.. 0]') (InputType: X, NarrowedType: X, DeclaredSymbol: null, LengthSymbol: System.Int32 X.Count { get; }, IndexerSymbol: System.Int32 X.this[System.Int32 i] { get; }) Patterns (1): ISlicePatternOperation (OperationKind.SlicePattern, Type: null, IsInvalid) (Syntax: '.. 0') (InputType: X, NarrowedType: X, SliceSymbol: System.Int32 X.this[System.Int32 i] { get; } Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '0') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') "; var expectedDiagnostics = new[] { // (9,32): error CS1503: Argument 1: cannot convert from 'System.Range' to 'int' // _ = /*<bind>*/this is [.. 0]/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, ".. 0").WithArguments("1", "System.Range", "int").WithLocation(9, 32) }; var comp = CreateCompilationWithIndexAndRange(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_ErrorCases_01() { string source = @" class X { void M(int[] a) { _ = /*<bind>*/a is ../*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'a is ..') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Pattern: ISlicePatternOperation (OperationKind.SlicePattern, Type: null, IsInvalid) (Syntax: '..') (InputType: System.Int32[], NarrowedType: System.Int32[], SliceSymbol: null Pattern: null "; var expectedDiagnostics = new[] { // (6,28): error CS9202: Slice patterns may only be used once and directly inside a list pattern. // _ = /*<bind>*/a is ../*</bind>*/; Diagnostic(ErrorCode.ERR_MisplacedSlicePattern, "..").WithLocation(6, 28) }; var comp = CreateCompilation(source); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_ErrorCases_02() { string source = @" class X { void M(int[] a) { _ = /*<bind>*/a is .. 42/*</bind>*/; } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'a is .. 42') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'a') Pattern: ISlicePatternOperation (OperationKind.SlicePattern, Type: null, IsInvalid) (Syntax: '.. 42') (InputType: System.Int32[], NarrowedType: System.Int32[], SliceSymbol: null Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '42') (InputType: System.Int32[], NarrowedType: System.Int32[]) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32[], IsInvalid, IsImplicit) (Syntax: '42') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42') "; var expectedDiagnostics = new[] { // (6,28): error CS9202: Slice patterns may only be used once and directly inside a list pattern. // _ = /*<bind>*/a is .. 42/*</bind>*/; Diagnostic(ErrorCode.ERR_MisplacedSlicePattern, ".. 42").WithLocation(6, 28), // (6,31): error CS0029: Cannot implicitly convert type 'int' to 'int[]' // _ = /*<bind>*/a is .. 42/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "42").WithArguments("int", "int[]").WithLocation(6, 31) }; var comp = CreateCompilation(new[] { source, TestSources.Index, TestSources.Range, TestSources.GetSubArray }); VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(comp, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsPatternExpression_ListPatterns_ControlFlow_01() { string source = @" class C { void M(int[] o) /*<bind>*/ { if (o is [1, .. var slice, 2]) { } }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32[]? slice] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B2] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'o is [1, .. ... r slice, 2]') Value: IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32[]) (Syntax: 'o') Pattern: IListPatternOperation (OperationKind.ListPattern, Type: null) (Syntax: '[1, .. var slice, 2]') (InputType: System.Int32[], NarrowedType: System.Int32[], DeclaredSymbol: null, LengthSymbol: System.Int32 System.Array.Length { get; }, IndexerSymbol: null) Patterns (3): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ISlicePatternOperation (OperationKind.SlicePattern, Type: null) (Syntax: '.. var slice') (InputType: System.Int32[], NarrowedType: System.Int32[], SliceSymbol: null Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var slice') (InputType: System.Int32[], NarrowedType: System.Int32[], DeclaredSymbol: System.Int32[]? slice, MatchesNull: True) IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '2') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Leaving: {R1} Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1*2] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(new[] { source, TestSources.Index, TestSources.Range, TestSources.GetSubArray }, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/Core/Portable/SimplifyTypeNames/SimplifyTypeNamesDiagnosticAnalyzerBase.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. // #define LOG using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; #if LOG using System.IO; using System.Text.RegularExpressions; #endif namespace Microsoft.CodeAnalysis.SimplifyTypeNames { internal abstract class SimplifyTypeNamesDiagnosticAnalyzerBase<TLanguageKindEnum> : DiagnosticAnalyzer, IBuiltInAnalyzer where TLanguageKindEnum : struct { #if LOG private static string _logFile = @"c:\temp\simplifytypenames.txt"; private static object _logGate = new object(); private static readonly Regex s_newlinePattern = new Regex(@"[\r\n]+"); #endif private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(WorkspacesResources.Name_can_be_simplified), WorkspacesResources.ResourceManager, typeof(WorkspacesResources)); private static readonly LocalizableString s_localizableTitleSimplifyNames = new LocalizableResourceString(nameof(FeaturesResources.Simplify_Names), FeaturesResources.ResourceManager, typeof(FeaturesResources)); private static readonly DiagnosticDescriptor s_descriptorSimplifyNames = new(IDEDiagnosticIds.SimplifyNamesDiagnosticId, s_localizableTitleSimplifyNames, s_localizableMessage, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.SimplifyNamesDiagnosticId), customTags: DiagnosticCustomTags.Unnecessary.Concat(EnforceOnBuildValues.SimplifyNames.ToCustomTag()).ToArray()); private static readonly LocalizableString s_localizableTitleSimplifyMemberAccess = new LocalizableResourceString(nameof(FeaturesResources.Simplify_Member_Access), FeaturesResources.ResourceManager, typeof(FeaturesResources)); private static readonly DiagnosticDescriptor s_descriptorSimplifyMemberAccess = new(IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId, s_localizableTitleSimplifyMemberAccess, s_localizableMessage, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId), customTags: DiagnosticCustomTags.Unnecessary.Concat(EnforceOnBuildValues.SimplifyMemberAccess.ToCustomTag()).ToArray()); private static readonly DiagnosticDescriptor s_descriptorPreferBuiltinOrFrameworkType = new(IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId, s_localizableTitleSimplifyNames, s_localizableMessage, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId), customTags: DiagnosticCustomTags.Unnecessary.Concat(EnforceOnBuildValues.PreferBuiltInOrFrameworkType.ToCustomTag()).ToArray()); internal abstract bool IsCandidate(SyntaxNode node); internal abstract bool CanSimplifyTypeNameExpression( SemanticModel model, SyntaxNode node, OptionSet optionSet, out TextSpan issueSpan, out string diagnosticId, out bool inDeclaration, CancellationToken cancellationToken); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create( s_descriptorSimplifyNames, s_descriptorSimplifyMemberAccess, s_descriptorPreferBuiltinOrFrameworkType); protected SimplifyTypeNamesDiagnosticAnalyzerBase() { } public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public bool OpenFileOnly(OptionSet options) { var preferTypeKeywordInDeclarationOption = options.GetOption( CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, GetLanguageName())!.Notification; var preferTypeKeywordInMemberAccessOption = options.GetOption( CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, GetLanguageName())!.Notification; return !(preferTypeKeywordInDeclarationOption == NotificationOption2.Warning || preferTypeKeywordInDeclarationOption == NotificationOption2.Error || preferTypeKeywordInMemberAccessOption == NotificationOption2.Warning || preferTypeKeywordInMemberAccessOption == NotificationOption2.Error); } public sealed override void Initialize(AnalysisContext context) { context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterCompilationStartAction(AnalyzeCompilation); } private void AnalyzeCompilation(CompilationStartAnalysisContext context) { var analyzer = new AnalyzerImpl(this); context.RegisterCodeBlockAction(analyzer.AnalyzeCodeBlock); context.RegisterSemanticModelAction(analyzer.AnalyzeSemanticModel); } /// <summary> /// Determine if a code block is eligible for analysis by <see cref="AnalyzeCodeBlock"/>. /// </summary> /// <param name="codeBlock">The syntax node provided via <see cref="CodeBlockAnalysisContext.CodeBlock"/>.</param> /// <returns><see langword="true"/> if the code block should be analyzed by <see cref="AnalyzeCodeBlock"/>; /// otherwise, <see langword="false"/> to skip analysis of the block. If a block is skipped, one or more child /// blocks may be analyzed by <see cref="AnalyzeCodeBlock"/>, and any remaining spans can be analyzed by /// <see cref="AnalyzeSemanticModel"/>.</returns> protected abstract bool IsIgnoredCodeBlock(SyntaxNode codeBlock); protected abstract ImmutableArray<Diagnostic> AnalyzeCodeBlock(CodeBlockAnalysisContext context); protected abstract ImmutableArray<Diagnostic> AnalyzeSemanticModel(SemanticModelAnalysisContext context, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? codeBlockIntervalTree); protected abstract string GetLanguageName(); public bool TrySimplify(SemanticModel model, SyntaxNode node, [NotNullWhen(true)] out Diagnostic? diagnostic, OptionSet optionSet, CancellationToken cancellationToken) { if (!CanSimplifyTypeNameExpression( model, node, optionSet, out var issueSpan, out var diagnosticId, out var inDeclaration, cancellationToken)) { diagnostic = null; return false; } if (model.SyntaxTree.OverlapsHiddenPosition(issueSpan, cancellationToken)) { diagnostic = null; return false; } diagnostic = CreateDiagnostic(model, optionSet, issueSpan, diagnosticId, inDeclaration); return true; } internal static Diagnostic CreateDiagnostic(SemanticModel model, OptionSet optionSet, TextSpan issueSpan, string diagnosticId, bool inDeclaration) { PerLanguageOption2<CodeStyleOption2<bool>> option; DiagnosticDescriptor descriptor; ReportDiagnostic severity; switch (diagnosticId) { case IDEDiagnosticIds.SimplifyNamesDiagnosticId: descriptor = s_descriptorSimplifyNames; severity = descriptor.DefaultSeverity.ToReportDiagnostic(); break; case IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId: descriptor = s_descriptorSimplifyMemberAccess; severity = descriptor.DefaultSeverity.ToReportDiagnostic(); break; case IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId: option = inDeclaration ? CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration : CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess; descriptor = s_descriptorPreferBuiltinOrFrameworkType; var optionValue = optionSet.GetOption(option, model.Language)!; severity = optionValue.Notification.Severity; break; default: throw ExceptionUtilities.UnexpectedValue(diagnosticId); } var tree = model.SyntaxTree; var builder = ImmutableDictionary.CreateBuilder<string, string?>(); builder["OptionName"] = nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); // TODO: need the actual one builder["OptionLanguage"] = model.Language; var diagnostic = DiagnosticHelper.Create(descriptor, tree.GetLocation(issueSpan), severity, additionalLocations: null, builder.ToImmutable()); #if LOG var sourceText = tree.GetText(); sourceText.GetLineAndOffset(issueSpan.Start, out var startLineNumber, out var startOffset); sourceText.GetLineAndOffset(issueSpan.End, out var endLineNumber, out var endOffset); var logLine = tree.FilePath + "," + startLineNumber + "\t" + diagnosticId + "\t" + inDeclaration + "\t"; var leading = sourceText.ToString(TextSpan.FromBounds( sourceText.Lines[startLineNumber].Start, issueSpan.Start)); var mid = sourceText.ToString(issueSpan); var trailing = sourceText.ToString(TextSpan.FromBounds( issueSpan.End, sourceText.Lines[endLineNumber].End)); var contents = leading + "[|" + s_newlinePattern.Replace(mid, " ") + "|]" + trailing; logLine += contents + "\r\n"; lock (_logGate) { File.AppendAllText(_logFile, logLine); } #endif return diagnostic; } public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private class AnalyzerImpl { private readonly SimplifyTypeNamesDiagnosticAnalyzerBase<TLanguageKindEnum> _analyzer; /// <summary> /// Tracks the analysis state of syntax trees in a compilation. Each syntax tree has the properties: /// <list type="bullet"> /// <item><description> /// <para><c>completed</c>: <see langword="true"/> to indicate that <c>intervalTree</c> has been obtained /// for use in a <see cref="SemanticModelAnalysisContext"/> callback; otherwise, <see langword="false"/> to /// indicate that <c>intervalTree</c> may be updated by adding a new non-overlapping <see cref="TextSpan"/> /// for analysis performed by a <see cref="CodeBlockAnalysisContext"/> callback.</para> /// /// <para>This field also serves as the lock object for updating both <c>completed</c> and /// <c>intervalTree</c>.</para> /// </description></item> /// <item><description> /// <para><c>intervalTree</c>: the set of intervals analyzed by <see cref="CodeBlockAnalysisContext"/> /// callbacks, and therefore do not need to be analyzed again by a /// <see cref="SemanticModelAnalysisContext"/> callback.</para> /// /// <para>This field may only be accessed while <c>completed</c> is locked, and is not valid after /// <c>completed</c> is <see langword="true"/>.</para> /// </description></item> /// </list> /// </summary> private readonly ConcurrentDictionary<SyntaxTree, (StrongBox<bool> completed, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? intervalTree)> _codeBlockIntervals = new(); public AnalyzerImpl(SimplifyTypeNamesDiagnosticAnalyzerBase<TLanguageKindEnum> analyzer) => _analyzer = analyzer; public void AnalyzeCodeBlock(CodeBlockAnalysisContext context) { if (_analyzer.IsIgnoredCodeBlock(context.CodeBlock)) return; var (completed, intervalTree) = _codeBlockIntervals.GetOrAdd(context.CodeBlock.SyntaxTree, _ => (new StrongBox<bool>(false), SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), Array.Empty<TextSpan>()))); if (completed.Value) return; RoslynDebug.AssertNotNull(intervalTree); if (!TryProceedWithInterval(addIfAvailable: false, context.CodeBlock.FullSpan, completed, intervalTree)) return; var diagnostics = _analyzer.AnalyzeCodeBlock(context); // After this point, cancellation is not allowed due to possible state alteration if (!TryProceedWithInterval(addIfAvailable: true, context.CodeBlock.FullSpan, completed, intervalTree)) return; foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } static bool TryProceedWithInterval(bool addIfAvailable, TextSpan span, StrongBox<bool> completed, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector> intervalTree) { lock (completed) { if (completed.Value) return false; if (intervalTree.HasIntervalThatOverlapsWith(span.Start, span.End)) return false; if (addIfAvailable) intervalTree.AddIntervalInPlace(span); return true; } } } public void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { // Get the state information for the syntax tree. If the state information is not available, it is // initialized directly to a completed state, ensuring that concurrent (or future) calls to // AnalyzeCodeBlock will always read completed==true, and intervalTree does not need to be initialized // to a non-null value. var (completed, intervalTree) = _codeBlockIntervals.GetOrAdd(context.SemanticModel.SyntaxTree, syntaxTree => (new StrongBox<bool>(true), null)); // Since SemanticModel callbacks only occur once per syntax tree, the completed state can be safely read // here. It will have one of the values: // // false: the state was initialized in AnalyzeCodeBlock, and intervalTree will be a non-null tree. // true: the state was initialized on the previous line, and either intervalTree will be null, or // a previous call to AnalyzeSemanticModel was cancelled and the new one will operate on the // same interval tree presented during the previous call. if (!completed.Value) { // This lock ensures we do not use intervalTree while it is being updated by a concurrent call to // AnalyzeCodeBlock. lock (completed) { // Prevent future code block callbacks from analyzing more spans within this tree completed.Value = true; } } var diagnostics = _analyzer.AnalyzeSemanticModel(context, intervalTree); // After this point, cancellation is not allowed due to possible state alteration foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } } } } }
// 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. // #define LOG using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; #if LOG using System.IO; using System.Text.RegularExpressions; #endif namespace Microsoft.CodeAnalysis.SimplifyTypeNames { internal abstract class SimplifyTypeNamesDiagnosticAnalyzerBase<TLanguageKindEnum> : DiagnosticAnalyzer, IBuiltInAnalyzer where TLanguageKindEnum : struct { #if LOG private static string _logFile = @"c:\temp\simplifytypenames.txt"; private static object _logGate = new object(); private static readonly Regex s_newlinePattern = new Regex(@"[\r\n]+"); #endif private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(WorkspacesResources.Name_can_be_simplified), WorkspacesResources.ResourceManager, typeof(WorkspacesResources)); private static readonly LocalizableString s_localizableTitleSimplifyNames = new LocalizableResourceString(nameof(FeaturesResources.Simplify_Names), FeaturesResources.ResourceManager, typeof(FeaturesResources)); private static readonly DiagnosticDescriptor s_descriptorSimplifyNames = new(IDEDiagnosticIds.SimplifyNamesDiagnosticId, s_localizableTitleSimplifyNames, s_localizableMessage, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.SimplifyNamesDiagnosticId), customTags: DiagnosticCustomTags.Unnecessary.Concat(EnforceOnBuildValues.SimplifyNames.ToCustomTag()).ToArray()); private static readonly LocalizableString s_localizableTitleSimplifyMemberAccess = new LocalizableResourceString(nameof(FeaturesResources.Simplify_Member_Access), FeaturesResources.ResourceManager, typeof(FeaturesResources)); private static readonly DiagnosticDescriptor s_descriptorSimplifyMemberAccess = new(IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId, s_localizableTitleSimplifyMemberAccess, s_localizableMessage, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId), customTags: DiagnosticCustomTags.Unnecessary.Concat(EnforceOnBuildValues.SimplifyMemberAccess.ToCustomTag()).ToArray()); private static readonly DiagnosticDescriptor s_descriptorPreferBuiltinOrFrameworkType = new(IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId, s_localizableTitleSimplifyNames, s_localizableMessage, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId), customTags: DiagnosticCustomTags.Unnecessary.Concat(EnforceOnBuildValues.PreferBuiltInOrFrameworkType.ToCustomTag()).ToArray()); internal abstract bool IsCandidate(SyntaxNode node); internal abstract bool CanSimplifyTypeNameExpression( SemanticModel model, SyntaxNode node, OptionSet optionSet, out TextSpan issueSpan, out string diagnosticId, out bool inDeclaration, CancellationToken cancellationToken); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create( s_descriptorSimplifyNames, s_descriptorSimplifyMemberAccess, s_descriptorPreferBuiltinOrFrameworkType); protected SimplifyTypeNamesDiagnosticAnalyzerBase() { } public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public bool OpenFileOnly(OptionSet options) { var preferTypeKeywordInDeclarationOption = options.GetOption( CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, GetLanguageName())!.Notification; var preferTypeKeywordInMemberAccessOption = options.GetOption( CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, GetLanguageName())!.Notification; return !(preferTypeKeywordInDeclarationOption == NotificationOption2.Warning || preferTypeKeywordInDeclarationOption == NotificationOption2.Error || preferTypeKeywordInMemberAccessOption == NotificationOption2.Warning || preferTypeKeywordInMemberAccessOption == NotificationOption2.Error); } public sealed override void Initialize(AnalysisContext context) { context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterCompilationStartAction(AnalyzeCompilation); } private void AnalyzeCompilation(CompilationStartAnalysisContext context) { var analyzer = new AnalyzerImpl(this); context.RegisterCodeBlockAction(analyzer.AnalyzeCodeBlock); context.RegisterSemanticModelAction(analyzer.AnalyzeSemanticModel); } /// <summary> /// Determine if a code block is eligible for analysis by <see cref="AnalyzeCodeBlock"/>. /// </summary> /// <param name="codeBlock">The syntax node provided via <see cref="CodeBlockAnalysisContext.CodeBlock"/>.</param> /// <returns><see langword="true"/> if the code block should be analyzed by <see cref="AnalyzeCodeBlock"/>; /// otherwise, <see langword="false"/> to skip analysis of the block. If a block is skipped, one or more child /// blocks may be analyzed by <see cref="AnalyzeCodeBlock"/>, and any remaining spans can be analyzed by /// <see cref="AnalyzeSemanticModel"/>.</returns> protected abstract bool IsIgnoredCodeBlock(SyntaxNode codeBlock); protected abstract ImmutableArray<Diagnostic> AnalyzeCodeBlock(CodeBlockAnalysisContext context); protected abstract ImmutableArray<Diagnostic> AnalyzeSemanticModel(SemanticModelAnalysisContext context, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? codeBlockIntervalTree); protected abstract string GetLanguageName(); public bool TrySimplify(SemanticModel model, SyntaxNode node, [NotNullWhen(true)] out Diagnostic? diagnostic, OptionSet optionSet, CancellationToken cancellationToken) { if (!CanSimplifyTypeNameExpression( model, node, optionSet, out var issueSpan, out var diagnosticId, out var inDeclaration, cancellationToken)) { diagnostic = null; return false; } if (model.SyntaxTree.OverlapsHiddenPosition(issueSpan, cancellationToken)) { diagnostic = null; return false; } diagnostic = CreateDiagnostic(model, optionSet, issueSpan, diagnosticId, inDeclaration); return true; } internal static Diagnostic CreateDiagnostic(SemanticModel model, OptionSet optionSet, TextSpan issueSpan, string diagnosticId, bool inDeclaration) { PerLanguageOption2<CodeStyleOption2<bool>> option; DiagnosticDescriptor descriptor; ReportDiagnostic severity; switch (diagnosticId) { case IDEDiagnosticIds.SimplifyNamesDiagnosticId: descriptor = s_descriptorSimplifyNames; severity = descriptor.DefaultSeverity.ToReportDiagnostic(); break; case IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId: descriptor = s_descriptorSimplifyMemberAccess; severity = descriptor.DefaultSeverity.ToReportDiagnostic(); break; case IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId: option = inDeclaration ? CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration : CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess; descriptor = s_descriptorPreferBuiltinOrFrameworkType; var optionValue = optionSet.GetOption(option, model.Language)!; severity = optionValue.Notification.Severity; break; default: throw ExceptionUtilities.UnexpectedValue(diagnosticId); } var tree = model.SyntaxTree; var builder = ImmutableDictionary.CreateBuilder<string, string?>(); builder["OptionName"] = nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); // TODO: need the actual one builder["OptionLanguage"] = model.Language; var diagnostic = DiagnosticHelper.Create(descriptor, tree.GetLocation(issueSpan), severity, additionalLocations: null, builder.ToImmutable()); #if LOG var sourceText = tree.GetText(); sourceText.GetLineAndOffset(issueSpan.Start, out var startLineNumber, out var startOffset); sourceText.GetLineAndOffset(issueSpan.End, out var endLineNumber, out var endOffset); var logLine = tree.FilePath + "," + startLineNumber + "\t" + diagnosticId + "\t" + inDeclaration + "\t"; var leading = sourceText.ToString(TextSpan.FromBounds( sourceText.Lines[startLineNumber].Start, issueSpan.Start)); var mid = sourceText.ToString(issueSpan); var trailing = sourceText.ToString(TextSpan.FromBounds( issueSpan.End, sourceText.Lines[endLineNumber].End)); var contents = leading + "[|" + s_newlinePattern.Replace(mid, " ") + "|]" + trailing; logLine += contents + "\r\n"; lock (_logGate) { File.AppendAllText(_logFile, logLine); } #endif return diagnostic; } public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private class AnalyzerImpl { private readonly SimplifyTypeNamesDiagnosticAnalyzerBase<TLanguageKindEnum> _analyzer; /// <summary> /// Tracks the analysis state of syntax trees in a compilation. Each syntax tree has the properties: /// <list type="bullet"> /// <item><description> /// <para><c>completed</c>: <see langword="true"/> to indicate that <c>intervalTree</c> has been obtained /// for use in a <see cref="SemanticModelAnalysisContext"/> callback; otherwise, <see langword="false"/> to /// indicate that <c>intervalTree</c> may be updated by adding a new non-overlapping <see cref="TextSpan"/> /// for analysis performed by a <see cref="CodeBlockAnalysisContext"/> callback.</para> /// /// <para>This field also serves as the lock object for updating both <c>completed</c> and /// <c>intervalTree</c>.</para> /// </description></item> /// <item><description> /// <para><c>intervalTree</c>: the set of intervals analyzed by <see cref="CodeBlockAnalysisContext"/> /// callbacks, and therefore do not need to be analyzed again by a /// <see cref="SemanticModelAnalysisContext"/> callback.</para> /// /// <para>This field may only be accessed while <c>completed</c> is locked, and is not valid after /// <c>completed</c> is <see langword="true"/>.</para> /// </description></item> /// </list> /// </summary> private readonly ConcurrentDictionary<SyntaxTree, (StrongBox<bool> completed, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? intervalTree)> _codeBlockIntervals = new(); public AnalyzerImpl(SimplifyTypeNamesDiagnosticAnalyzerBase<TLanguageKindEnum> analyzer) => _analyzer = analyzer; public void AnalyzeCodeBlock(CodeBlockAnalysisContext context) { if (_analyzer.IsIgnoredCodeBlock(context.CodeBlock)) return; var (completed, intervalTree) = _codeBlockIntervals.GetOrAdd(context.CodeBlock.SyntaxTree, _ => (new StrongBox<bool>(false), SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), Array.Empty<TextSpan>()))); if (completed.Value) return; RoslynDebug.AssertNotNull(intervalTree); if (!TryProceedWithInterval(addIfAvailable: false, context.CodeBlock.FullSpan, completed, intervalTree)) return; var diagnostics = _analyzer.AnalyzeCodeBlock(context); // After this point, cancellation is not allowed due to possible state alteration if (!TryProceedWithInterval(addIfAvailable: true, context.CodeBlock.FullSpan, completed, intervalTree)) return; foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } static bool TryProceedWithInterval(bool addIfAvailable, TextSpan span, StrongBox<bool> completed, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector> intervalTree) { lock (completed) { if (completed.Value) return false; if (intervalTree.HasIntervalThatOverlapsWith(span.Start, span.End)) return false; if (addIfAvailable) intervalTree.AddIntervalInPlace(span); return true; } } } public void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { // Get the state information for the syntax tree. If the state information is not available, it is // initialized directly to a completed state, ensuring that concurrent (or future) calls to // AnalyzeCodeBlock will always read completed==true, and intervalTree does not need to be initialized // to a non-null value. var (completed, intervalTree) = _codeBlockIntervals.GetOrAdd(context.SemanticModel.SyntaxTree, syntaxTree => (new StrongBox<bool>(true), null)); // Since SemanticModel callbacks only occur once per syntax tree, the completed state can be safely read // here. It will have one of the values: // // false: the state was initialized in AnalyzeCodeBlock, and intervalTree will be a non-null tree. // true: the state was initialized on the previous line, and either intervalTree will be null, or // a previous call to AnalyzeSemanticModel was cancelled and the new one will operate on the // same interval tree presented during the previous call. if (!completed.Value) { // This lock ensures we do not use intervalTree while it is being updated by a concurrent call to // AnalyzeCodeBlock. lock (completed) { // Prevent future code block callbacks from analyzing more spans within this tree completed.Value = true; } } var diagnostics = _analyzer.AnalyzeSemanticModel(context, intervalTree); // After this point, cancellation is not allowed due to possible state alteration foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/LanguageServer/Protocol/Handler/Formatting/FormatDocumentRangeHandler.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(Methods.TextDocumentRangeFormattingName)] internal class FormatDocumentRangeHandler : AbstractFormatDocumentHandlerBase<DocumentRangeFormattingParams, TextEdit[]?> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FormatDocumentRangeHandler() { } public override string Method => Methods.TextDocumentRangeFormattingName; public override TextDocumentIdentifier? GetTextDocumentIdentifier(DocumentRangeFormattingParams request) => request.TextDocument; public override Task<TextEdit[]?> HandleRequestAsync( DocumentRangeFormattingParams request, RequestContext context, CancellationToken cancellationToken) => GetTextEditsAsync(context, request.Options, cancellationToken, range: request.Range); } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(Methods.TextDocumentRangeFormattingName)] internal class FormatDocumentRangeHandler : AbstractFormatDocumentHandlerBase<DocumentRangeFormattingParams, TextEdit[]?> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FormatDocumentRangeHandler() { } public override string Method => Methods.TextDocumentRangeFormattingName; public override TextDocumentIdentifier? GetTextDocumentIdentifier(DocumentRangeFormattingParams request) => request.TextDocument; public override Task<TextEdit[]?> HandleRequestAsync( DocumentRangeFormattingParams request, RequestContext context, CancellationToken cancellationToken) => GetTextEditsAsync(context, request.Options, cancellationToken, range: request.Range); } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/Portable/FileSystem/PathUtilities.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.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Roslyn.Utilities { // Contains path parsing utilities. // We need our own because System.IO.Path is insufficient for our purposes // For example we need to be able to work with invalid paths or paths containing wildcards internal static class PathUtilities { // We consider '/' a directory separator on Unix like systems. // On Windows both / and \ are equally accepted. internal static readonly char DirectorySeparatorChar = PlatformInformation.IsUnix ? '/' : '\\'; internal const char AltDirectorySeparatorChar = '/'; internal const string ParentRelativeDirectory = ".."; internal const string ThisDirectory = "."; internal static readonly string DirectorySeparatorStr = new(DirectorySeparatorChar, 1); internal const char VolumeSeparatorChar = ':'; internal static bool IsUnixLikePlatform => PlatformInformation.IsUnix; /// <summary> /// True if the character is the platform directory separator character or the alternate directory separator. /// </summary> public static bool IsDirectorySeparator(char c) => c == DirectorySeparatorChar || c == AltDirectorySeparatorChar; /// <summary> /// True if the character is any recognized directory separator character. /// </summary> public static bool IsAnyDirectorySeparator(char c) => c == '\\' || c == '/'; /// <summary> /// Removes trailing directory separator characters /// </summary> /// <remarks> /// This will trim the root directory separator: /// "C:\" maps to "C:", and "/" maps to "" /// </remarks> public static string TrimTrailingSeparators(string s) { int lastSeparator = s.Length; while (lastSeparator > 0 && IsDirectorySeparator(s[lastSeparator - 1])) { lastSeparator -= 1; } if (lastSeparator != s.Length) { s = s.Substring(0, lastSeparator); } return s; } /// <summary> /// Ensures a trailing directory separator character /// </summary> public static string EnsureTrailingSeparator(string s) { if (s.Length == 0 || IsAnyDirectorySeparator(s[s.Length - 1])) { return s; } // Use the existing slashes in the path, if they're consistent bool hasSlash = s.IndexOf('/') >= 0; bool hasBackslash = s.IndexOf('\\') >= 0; if (hasSlash && !hasBackslash) { return s + '/'; } else if (!hasSlash && hasBackslash) { return s + '\\'; } else { // If there are no slashes or they are inconsistent, use the current platform's slash. return s + DirectorySeparatorChar; } } public static string GetExtension(string path) { return FileNameUtilities.GetExtension(path); } public static ReadOnlyMemory<char> GetExtension(ReadOnlyMemory<char> path) { return FileNameUtilities.GetExtension(path); } public static string ChangeExtension(string path, string? extension) { return FileNameUtilities.ChangeExtension(path, extension); } public static string RemoveExtension(string path) { return FileNameUtilities.ChangeExtension(path, extension: null); } [return: NotNullIfNotNull(parameterName: "path")] public static string? GetFileName(string? path, bool includeExtension = true) { return FileNameUtilities.GetFileName(path, includeExtension); } /// <summary> /// Get directory name from path. /// </summary> /// <remarks> /// Unlike <see cref="System.IO.Path.GetDirectoryName(string)"/> it doesn't check for invalid path characters /// </remarks> /// <returns>Prefix of path that represents a directory</returns> public static string? GetDirectoryName(string? path) { return GetDirectoryName(path, IsUnixLikePlatform); } internal static string? GetDirectoryName(string? path, bool isUnixLike) { if (path != null) { var rootLength = GetPathRoot(path, isUnixLike).Length; if (path.Length > rootLength) { var i = path.Length; while (i > rootLength) { i--; if (IsDirectorySeparator(path[i])) { if (i > 0 && IsDirectorySeparator(path[i - 1])) { continue; } break; } } return path.Substring(0, i); } } return null; } internal static bool IsSameDirectoryOrChildOf(string child, string parent) { parent = RemoveTrailingDirectorySeparator(parent); string? currentChild = child; while (currentChild != null) { currentChild = RemoveTrailingDirectorySeparator(currentChild); if (currentChild.Equals(parent, StringComparison.OrdinalIgnoreCase)) { return true; } currentChild = GetDirectoryName(currentChild); } return false; } /// <summary> /// Gets the root part of the path. /// </summary> [return: NotNullIfNotNull(parameterName: "path")] public static string? GetPathRoot(string? path) { return GetPathRoot(path, IsUnixLikePlatform); } [return: NotNullIfNotNull(parameterName: "path")] private static string? GetPathRoot(string? path, bool isUnixLike) { if (path == null) { return null; } if (isUnixLike) { return GetUnixRoot(path); } else { return GetWindowsRoot(path); } } private static string GetWindowsRoot(string path) { // Windows int length = path.Length; if (length >= 1 && IsDirectorySeparator(path[0])) { if (length < 2 || !IsDirectorySeparator(path[1])) { // It was of the form: // \ // \f // in this case, just return \ as the root. return path.Substring(0, 1); } // First consume all directory separators. int i = 2; i = ConsumeDirectorySeparators(path, length, i); // We've got \\ so far. If we have a path of the form \\x\y\z // then we want to return "\\x\y" as the root portion. bool hitSeparator = false; while (true) { if (i == length) { // We reached the end of the path. The entire path is // considered the root. return path; } if (!IsDirectorySeparator(path[i])) { // We got a non separator character. Just keep consuming. i++; continue; } if (!hitSeparator) { // This is the first separator group we've hit after some server path. // Consume them and keep going. hitSeparator = true; i = ConsumeDirectorySeparators(path, length, i); continue; } // We hit the second separator. The root is the path up to this point. return path.Substring(0, i); } } else if (length >= 2 && path[1] == VolumeSeparatorChar) { // handles c: and c:\ return length >= 3 && IsDirectorySeparator(path[2]) ? path.Substring(0, 3) : path.Substring(0, 2); } else { // No path root. return ""; } } private static int ConsumeDirectorySeparators(string path, int length, int i) { while (i < length && IsDirectorySeparator(path[i])) { i++; } return i; } private static string GetUnixRoot(string path) { // either it starts with "/" and thus has "/" as the root. Or it has no root. return path.Length > 0 && IsDirectorySeparator(path[0]) ? path.Substring(0, 1) : ""; } /// <summary> /// Gets the specific kind of relative or absolute path. /// </summary> public static PathKind GetPathKind(string? path) { if (RoslynString.IsNullOrWhiteSpace(path)) { return PathKind.Empty; } // "C:\" // "\\machine" (UNC) // "/etc" (Unix) if (IsAbsolute(path)) { return PathKind.Absolute; } // "." // ".." // ".\" // "..\" if (path.Length > 0 && path[0] == '.') { if (path.Length == 1 || IsDirectorySeparator(path[1])) { return PathKind.RelativeToCurrentDirectory; } if (path[1] == '.') { if (path.Length == 2 || IsDirectorySeparator(path[2])) { return PathKind.RelativeToCurrentParent; } } } if (!IsUnixLikePlatform) { // "\" // "\goo" if (path.Length >= 1 && IsDirectorySeparator(path[0])) { return PathKind.RelativeToCurrentRoot; } // "C:goo" if (path.Length >= 2 && path[1] == VolumeSeparatorChar && (path.Length <= 2 || !IsDirectorySeparator(path[2]))) { return PathKind.RelativeToDriveDirectory; } } // "goo.dll" return PathKind.Relative; } /// <summary> /// True if the path is an absolute path (rooted to drive or network share) /// </summary> public static bool IsAbsolute([NotNullWhen(true)] string? path) { if (RoslynString.IsNullOrEmpty(path)) { return false; } if (IsUnixLikePlatform) { return path[0] == DirectorySeparatorChar; } // "C:\" if (IsDriveRootedAbsolutePath(path)) { // Including invalid paths (e.g. "*:\") return true; } // "\\machine\share" // Including invalid/incomplete UNC paths (e.g. "\\goo") return path.Length >= 2 && IsDirectorySeparator(path[0]) && IsDirectorySeparator(path[1]); } /// <summary> /// Returns true if given path is absolute and starts with a drive specification ("C:\"). /// </summary> private static bool IsDriveRootedAbsolutePath(string path) { Debug.Assert(!IsUnixLikePlatform); return path.Length >= 3 && path[1] == VolumeSeparatorChar && IsDirectorySeparator(path[2]); } /// <summary> /// Combines an absolute path with a relative. /// </summary> /// <param name="root">Absolute root path.</param> /// <param name="relativePath">Relative path.</param> /// <returns> /// An absolute combined path, or null if <paramref name="relativePath"/> is /// absolute (e.g. "C:\abc", "\\machine\share\abc"), /// relative to the current root (e.g. "\abc"), /// or relative to a drive directory (e.g. "C:abc\def"). /// </returns> /// <seealso cref="CombinePossiblyRelativeAndRelativePaths"/> public static string? CombineAbsoluteAndRelativePaths(string root, string relativePath) { Debug.Assert(IsAbsolute(root)); return CombinePossiblyRelativeAndRelativePaths(root, relativePath); } /// <summary> /// Combine two paths, the first of which may be absolute. /// </summary> /// <param name="root">First path: absolute, relative, or null.</param> /// <param name="relativePath">Second path: relative and non-null.</param> /// <returns>null, if <paramref name="root"/> is null; a combined path, otherwise.</returns> /// <seealso cref="CombineAbsoluteAndRelativePaths"/> public static string? CombinePossiblyRelativeAndRelativePaths(string? root, string? relativePath) { if (RoslynString.IsNullOrEmpty(root)) { return null; } switch (GetPathKind(relativePath)) { case PathKind.Empty: return root; case PathKind.Absolute: case PathKind.RelativeToCurrentRoot: case PathKind.RelativeToDriveDirectory: return null; } return CombinePathsUnchecked(root, relativePath); } public static string CombinePathsUnchecked(string root, string? relativePath) { RoslynDebug.Assert(!RoslynString.IsNullOrEmpty(root)); char c = root[root.Length - 1]; if (!IsDirectorySeparator(c) && c != VolumeSeparatorChar) { return root + DirectorySeparatorStr + relativePath; } return root + relativePath; } /// <summary> /// Combines paths with the same semantics as <see cref="Path.Combine(string, string)"/> /// but does not throw on null paths or paths with invalid characters. /// </summary> /// <param name="root">First path: absolute, relative, or null.</param> /// <param name="path">Second path: absolute, relative, or null.</param> /// <returns> /// The combined paths. If <paramref name="path"/> contains an absolute path, returns <paramref name="path"/>. /// </returns> /// <remarks> /// Relative and absolute paths treated the same as <see cref="Path.Combine(string, string)"/>. /// </remarks> [return: NotNullIfNotNull("path")] public static string? CombinePaths(string? root, string? path) { if (RoslynString.IsNullOrEmpty(root)) { return path; } if (RoslynString.IsNullOrEmpty(path)) { return root; } return IsAbsolute(path) ? path : CombinePathsUnchecked(root, path); } private static string RemoveTrailingDirectorySeparator(string path) { if (path.Length > 0 && IsDirectorySeparator(path[path.Length - 1])) { return path.Substring(0, path.Length - 1); } else { return path; } } /// <summary> /// Determines whether an assembly reference is considered an assembly file path or an assembly name. /// used, for example, on values of /r and #r. /// </summary> public static bool IsFilePath(string assemblyDisplayNameOrPath) { RoslynDebug.Assert(assemblyDisplayNameOrPath != null); string? extension = FileNameUtilities.GetExtension(assemblyDisplayNameOrPath); return string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".exe", StringComparison.OrdinalIgnoreCase) || assemblyDisplayNameOrPath.IndexOf(DirectorySeparatorChar) != -1 || assemblyDisplayNameOrPath.IndexOf(AltDirectorySeparatorChar) != -1; } /// <summary> /// Determines if "path" contains 'component' within itself. /// i.e. asking if the path "c:\goo\bar\baz" has component "bar" would return 'true'. /// On the other hand, if you had "c:\goo\bar1\baz" then it would not have "bar" as a /// component. /// /// A path contains a component if any file name or directory name in the path /// matches 'component'. As such, if you had something like "\\goo" then that would /// not have "goo" as a component. That's because here "goo" is the server name portion /// of the UNC path, and not an actual directory or file name. /// </summary> public static bool ContainsPathComponent(string? path, string component, bool ignoreCase) { var comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; if (path?.IndexOf(component, comparison) >= 0) { var comparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; int count = 0; string? currentPath = path; while (currentPath != null) { var currentName = GetFileName(currentPath); if (comparer.Equals(currentName, component)) { return true; } currentPath = GetDirectoryName(currentPath); count++; } } return false; } /// <summary> /// Gets a path relative to a directory. /// </summary> public static string GetRelativePath(string directory, string fullPath) { string relativePath = string.Empty; directory = TrimTrailingSeparators(directory); fullPath = TrimTrailingSeparators(fullPath); if (IsChildPath(directory, fullPath)) { return GetRelativeChildPath(directory, fullPath); } var directoryPathParts = GetPathParts(directory); var fullPathParts = GetPathParts(fullPath); if (directoryPathParts.Length == 0 || fullPathParts.Length == 0) { return fullPath; } int index = 0; // find index where full path diverges from base path for (; index < directoryPathParts.Length; index++) { if (!PathsEqual(directoryPathParts[index], fullPathParts[index])) { break; } } // if the first part doesn't match, they don't even have the same volume // so there can be no relative path. if (index == 0) { return fullPath; } // add backup notation for remaining base path levels beyond the index var remainingParts = directoryPathParts.Length - index; if (remainingParts > 0) { for (int i = 0; i < remainingParts; i++) { relativePath = relativePath + ParentRelativeDirectory + DirectorySeparatorStr; } } // add the rest of the full path parts for (int i = index; i < fullPathParts.Length; i++) { relativePath = CombinePathsUnchecked(relativePath, fullPathParts[i]); } return relativePath; } /// <summary> /// True if the child path is a child of the parent path. /// </summary> public static bool IsChildPath(string parentPath, string childPath) { return parentPath.Length > 0 && childPath.Length > parentPath.Length && PathsEqual(childPath, parentPath, parentPath.Length) && (IsDirectorySeparator(parentPath[parentPath.Length - 1]) || IsDirectorySeparator(childPath[parentPath.Length])); } private static string GetRelativeChildPath(string parentPath, string childPath) { var relativePath = childPath.Substring(parentPath.Length); // trim any leading separators left over after removing leading directory int start = ConsumeDirectorySeparators(relativePath, relativePath.Length, 0); if (start > 0) { relativePath = relativePath.Substring(start); } return relativePath; } private static readonly char[] s_pathChars = new char[] { VolumeSeparatorChar, DirectorySeparatorChar, AltDirectorySeparatorChar }; private static string[] GetPathParts(string path) { var pathParts = path.Split(s_pathChars); // remove references to self directories ('.') if (pathParts.Contains(ThisDirectory)) { pathParts = pathParts.Where(s => s != ThisDirectory).ToArray(); } return pathParts; } /// <summary> /// True if the two paths are the same. /// </summary> public static bool PathsEqual(string path1, string path2) { return PathsEqual(path1, path2, Math.Max(path1.Length, path2.Length)); } /// <summary> /// True if the two paths are the same. (but only up to the specified length) /// </summary> private static bool PathsEqual(string path1, string path2, int length) { if (path1.Length < length || path2.Length < length) { return false; } for (int i = 0; i < length; i++) { if (!PathCharEqual(path1[i], path2[i])) { return false; } } return true; } private static bool PathCharEqual(char x, char y) { if (IsDirectorySeparator(x) && IsDirectorySeparator(y)) { return true; } return IsUnixLikePlatform ? x == y : char.ToUpperInvariant(x) == char.ToUpperInvariant(y); } private static int PathHashCode(string? path) { int hc = 0; if (path != null) { foreach (var ch in path) { if (!IsDirectorySeparator(ch)) { hc = Hash.Combine(char.ToUpperInvariant(ch), hc); } } } return hc; } public static string NormalizePathPrefix(string filePath, ImmutableArray<KeyValuePair<string, string>> pathMap) { if (pathMap.IsDefaultOrEmpty) { return filePath; } // find the first key in the path map that matches a prefix of the normalized path. // Note that we expect the client to use consistent capitalization; we use ordinal (case-sensitive) comparisons. foreach (var kv in pathMap) { var oldPrefix = kv.Key; if (!(oldPrefix?.Length > 0)) continue; // oldPrefix always ends with a path separator, so there's no need to check if it was a partial match // e.g. for the map /goo=/bar and filename /goooo if (filePath.StartsWith(oldPrefix, StringComparison.Ordinal)) { var replacementPrefix = kv.Value; // Replace that prefix. var replacement = replacementPrefix + filePath.Substring(oldPrefix.Length); // Normalize the path separators if used uniformly in the replacement bool hasSlash = replacementPrefix.IndexOf('/') >= 0; bool hasBackslash = replacementPrefix.IndexOf('\\') >= 0; return (hasSlash && !hasBackslash) ? replacement.Replace('\\', '/') : (hasBackslash && !hasSlash) ? replacement.Replace('/', '\\') : replacement; } } return filePath; } /// <summary> /// Unfortunately, we cannot depend on Path.GetInvalidPathChars() or Path.GetInvalidFileNameChars() /// From MSDN: The array returned from this method is not guaranteed to contain the complete set of characters /// that are invalid in file and directory names. The full set of invalid characters can vary by file system. /// https://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx /// /// Additionally, Path.GetInvalidPathChars() doesn't include "?" or "*" which are invalid characters, /// and Path.GetInvalidFileNameChars() includes ":" and "\" which are valid characters. /// /// The more accurate way is to let the framework parse the path and throw on any errors. /// </summary> public static bool IsValidFilePath([NotNullWhen(true)] string? fullPath) { try { if (RoslynString.IsNullOrEmpty(fullPath)) { return false; } // Uncomment when this is fixed: https://github.com/dotnet/roslyn/issues/19592 // Debug.Assert(IsAbsolute(fullPath)); var fileInfo = new FileInfo(fullPath); return !string.IsNullOrEmpty(fileInfo.Name); } catch (Exception ex) when ( ex is ArgumentException || // The file name is empty, contains only white spaces, or contains invalid characters. ex is PathTooLongException || // The specified path, file name, or both exceed the system-defined maximum length. ex is NotSupportedException) // fileName contains a colon (:) in the middle of the string. { return false; } } /// <summary> /// If the current environment uses the '\' directory separator, replaces all uses of '\' /// in the given string with '/'. Otherwise, returns the string. /// </summary> /// <remarks> /// This method is equivalent to Microsoft.CodeAnalysis.BuildTasks.GenerateMSBuildEditorConfig.NormalizeWithForwardSlash /// Both methods should be kept in sync. /// </remarks> public static string NormalizeWithForwardSlash(string p) => DirectorySeparatorChar == '/' ? p : p.Replace(DirectorySeparatorChar, '/'); /// <summary> /// Takes an absolute path and attempts to expand any '..' or '.' into their equivalent representation. /// </summary> /// <returns>An equivalent path that does not contain any '..' or '.' path parts, or the original path.</returns> /// <remarks> /// This method handles unix and windows drive rooted absolute paths only (i.e /a/b or x:\a\b). Passing any other kind of path /// including relative, drive relative, unc, or windows device paths will simply return the original input. /// </remarks> public static string ExpandAbsolutePathWithRelativeParts(string p) { bool isDriveRooted = !IsUnixLikePlatform && IsDriveRootedAbsolutePath(p); if (!isDriveRooted && !(p.Length > 1 && p[0] == AltDirectorySeparatorChar)) { // if this isn't a regular absolute path we can't expand it correctly return p; } // GetPathParts also removes any instances of '.' var parts = GetPathParts(p); // For drive rooted paths we need to skip the volume specifier, but remember it for re-joining later var volumeSpecifier = isDriveRooted ? p.Substring(0, 2) : string.Empty; // Skip the root directory var toSkip = isDriveRooted ? 2 : 1; Debug.Assert(parts[toSkip - 1] == string.Empty); var resolvedParts = ArrayBuilder<string>.GetInstance(); foreach (var part in parts.Skip(toSkip)) { if (!part.Equals(ParentRelativeDirectory)) { resolvedParts.Push(part); } // /../../file is considered equal to /file, so we only process the parent relative directory info if there is actually a parent else if (resolvedParts.Count > 0) { resolvedParts.Pop(); } } var expandedPath = volumeSpecifier + '/' + string.Join("/", resolvedParts); resolvedParts.Free(); return expandedPath; } public static readonly IEqualityComparer<string> Comparer = new PathComparer(); private class PathComparer : IEqualityComparer<string?> { public bool Equals(string? x, string? y) { if (x == null && y == null) { return true; } if (x == null || y == null) { return false; } return PathsEqual(x, y); } public int GetHashCode(string? s) { return PathHashCode(s); } } internal static class TestAccessor { internal static string? GetDirectoryName(string path, bool isUnixLike) => PathUtilities.GetDirectoryName(path, isUnixLike); } } }
// 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.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Roslyn.Utilities { // Contains path parsing utilities. // We need our own because System.IO.Path is insufficient for our purposes // For example we need to be able to work with invalid paths or paths containing wildcards internal static class PathUtilities { // We consider '/' a directory separator on Unix like systems. // On Windows both / and \ are equally accepted. internal static readonly char DirectorySeparatorChar = PlatformInformation.IsUnix ? '/' : '\\'; internal const char AltDirectorySeparatorChar = '/'; internal const string ParentRelativeDirectory = ".."; internal const string ThisDirectory = "."; internal static readonly string DirectorySeparatorStr = new(DirectorySeparatorChar, 1); internal const char VolumeSeparatorChar = ':'; internal static bool IsUnixLikePlatform => PlatformInformation.IsUnix; /// <summary> /// True if the character is the platform directory separator character or the alternate directory separator. /// </summary> public static bool IsDirectorySeparator(char c) => c == DirectorySeparatorChar || c == AltDirectorySeparatorChar; /// <summary> /// True if the character is any recognized directory separator character. /// </summary> public static bool IsAnyDirectorySeparator(char c) => c == '\\' || c == '/'; /// <summary> /// Removes trailing directory separator characters /// </summary> /// <remarks> /// This will trim the root directory separator: /// "C:\" maps to "C:", and "/" maps to "" /// </remarks> public static string TrimTrailingSeparators(string s) { int lastSeparator = s.Length; while (lastSeparator > 0 && IsDirectorySeparator(s[lastSeparator - 1])) { lastSeparator -= 1; } if (lastSeparator != s.Length) { s = s.Substring(0, lastSeparator); } return s; } /// <summary> /// Ensures a trailing directory separator character /// </summary> public static string EnsureTrailingSeparator(string s) { if (s.Length == 0 || IsAnyDirectorySeparator(s[s.Length - 1])) { return s; } // Use the existing slashes in the path, if they're consistent bool hasSlash = s.IndexOf('/') >= 0; bool hasBackslash = s.IndexOf('\\') >= 0; if (hasSlash && !hasBackslash) { return s + '/'; } else if (!hasSlash && hasBackslash) { return s + '\\'; } else { // If there are no slashes or they are inconsistent, use the current platform's slash. return s + DirectorySeparatorChar; } } public static string GetExtension(string path) { return FileNameUtilities.GetExtension(path); } public static ReadOnlyMemory<char> GetExtension(ReadOnlyMemory<char> path) { return FileNameUtilities.GetExtension(path); } public static string ChangeExtension(string path, string? extension) { return FileNameUtilities.ChangeExtension(path, extension); } public static string RemoveExtension(string path) { return FileNameUtilities.ChangeExtension(path, extension: null); } [return: NotNullIfNotNull(parameterName: "path")] public static string? GetFileName(string? path, bool includeExtension = true) { return FileNameUtilities.GetFileName(path, includeExtension); } /// <summary> /// Get directory name from path. /// </summary> /// <remarks> /// Unlike <see cref="System.IO.Path.GetDirectoryName(string)"/> it doesn't check for invalid path characters /// </remarks> /// <returns>Prefix of path that represents a directory</returns> public static string? GetDirectoryName(string? path) { return GetDirectoryName(path, IsUnixLikePlatform); } internal static string? GetDirectoryName(string? path, bool isUnixLike) { if (path != null) { var rootLength = GetPathRoot(path, isUnixLike).Length; if (path.Length > rootLength) { var i = path.Length; while (i > rootLength) { i--; if (IsDirectorySeparator(path[i])) { if (i > 0 && IsDirectorySeparator(path[i - 1])) { continue; } break; } } return path.Substring(0, i); } } return null; } internal static bool IsSameDirectoryOrChildOf(string child, string parent) { parent = RemoveTrailingDirectorySeparator(parent); string? currentChild = child; while (currentChild != null) { currentChild = RemoveTrailingDirectorySeparator(currentChild); if (currentChild.Equals(parent, StringComparison.OrdinalIgnoreCase)) { return true; } currentChild = GetDirectoryName(currentChild); } return false; } /// <summary> /// Gets the root part of the path. /// </summary> [return: NotNullIfNotNull(parameterName: "path")] public static string? GetPathRoot(string? path) { return GetPathRoot(path, IsUnixLikePlatform); } [return: NotNullIfNotNull(parameterName: "path")] private static string? GetPathRoot(string? path, bool isUnixLike) { if (path == null) { return null; } if (isUnixLike) { return GetUnixRoot(path); } else { return GetWindowsRoot(path); } } private static string GetWindowsRoot(string path) { // Windows int length = path.Length; if (length >= 1 && IsDirectorySeparator(path[0])) { if (length < 2 || !IsDirectorySeparator(path[1])) { // It was of the form: // \ // \f // in this case, just return \ as the root. return path.Substring(0, 1); } // First consume all directory separators. int i = 2; i = ConsumeDirectorySeparators(path, length, i); // We've got \\ so far. If we have a path of the form \\x\y\z // then we want to return "\\x\y" as the root portion. bool hitSeparator = false; while (true) { if (i == length) { // We reached the end of the path. The entire path is // considered the root. return path; } if (!IsDirectorySeparator(path[i])) { // We got a non separator character. Just keep consuming. i++; continue; } if (!hitSeparator) { // This is the first separator group we've hit after some server path. // Consume them and keep going. hitSeparator = true; i = ConsumeDirectorySeparators(path, length, i); continue; } // We hit the second separator. The root is the path up to this point. return path.Substring(0, i); } } else if (length >= 2 && path[1] == VolumeSeparatorChar) { // handles c: and c:\ return length >= 3 && IsDirectorySeparator(path[2]) ? path.Substring(0, 3) : path.Substring(0, 2); } else { // No path root. return ""; } } private static int ConsumeDirectorySeparators(string path, int length, int i) { while (i < length && IsDirectorySeparator(path[i])) { i++; } return i; } private static string GetUnixRoot(string path) { // either it starts with "/" and thus has "/" as the root. Or it has no root. return path.Length > 0 && IsDirectorySeparator(path[0]) ? path.Substring(0, 1) : ""; } /// <summary> /// Gets the specific kind of relative or absolute path. /// </summary> public static PathKind GetPathKind(string? path) { if (RoslynString.IsNullOrWhiteSpace(path)) { return PathKind.Empty; } // "C:\" // "\\machine" (UNC) // "/etc" (Unix) if (IsAbsolute(path)) { return PathKind.Absolute; } // "." // ".." // ".\" // "..\" if (path.Length > 0 && path[0] == '.') { if (path.Length == 1 || IsDirectorySeparator(path[1])) { return PathKind.RelativeToCurrentDirectory; } if (path[1] == '.') { if (path.Length == 2 || IsDirectorySeparator(path[2])) { return PathKind.RelativeToCurrentParent; } } } if (!IsUnixLikePlatform) { // "\" // "\goo" if (path.Length >= 1 && IsDirectorySeparator(path[0])) { return PathKind.RelativeToCurrentRoot; } // "C:goo" if (path.Length >= 2 && path[1] == VolumeSeparatorChar && (path.Length <= 2 || !IsDirectorySeparator(path[2]))) { return PathKind.RelativeToDriveDirectory; } } // "goo.dll" return PathKind.Relative; } /// <summary> /// True if the path is an absolute path (rooted to drive or network share) /// </summary> public static bool IsAbsolute([NotNullWhen(true)] string? path) { if (RoslynString.IsNullOrEmpty(path)) { return false; } if (IsUnixLikePlatform) { return path[0] == DirectorySeparatorChar; } // "C:\" if (IsDriveRootedAbsolutePath(path)) { // Including invalid paths (e.g. "*:\") return true; } // "\\machine\share" // Including invalid/incomplete UNC paths (e.g. "\\goo") return path.Length >= 2 && IsDirectorySeparator(path[0]) && IsDirectorySeparator(path[1]); } /// <summary> /// Returns true if given path is absolute and starts with a drive specification ("C:\"). /// </summary> private static bool IsDriveRootedAbsolutePath(string path) { Debug.Assert(!IsUnixLikePlatform); return path.Length >= 3 && path[1] == VolumeSeparatorChar && IsDirectorySeparator(path[2]); } /// <summary> /// Combines an absolute path with a relative. /// </summary> /// <param name="root">Absolute root path.</param> /// <param name="relativePath">Relative path.</param> /// <returns> /// An absolute combined path, or null if <paramref name="relativePath"/> is /// absolute (e.g. "C:\abc", "\\machine\share\abc"), /// relative to the current root (e.g. "\abc"), /// or relative to a drive directory (e.g. "C:abc\def"). /// </returns> /// <seealso cref="CombinePossiblyRelativeAndRelativePaths"/> public static string? CombineAbsoluteAndRelativePaths(string root, string relativePath) { Debug.Assert(IsAbsolute(root)); return CombinePossiblyRelativeAndRelativePaths(root, relativePath); } /// <summary> /// Combine two paths, the first of which may be absolute. /// </summary> /// <param name="root">First path: absolute, relative, or null.</param> /// <param name="relativePath">Second path: relative and non-null.</param> /// <returns>null, if <paramref name="root"/> is null; a combined path, otherwise.</returns> /// <seealso cref="CombineAbsoluteAndRelativePaths"/> public static string? CombinePossiblyRelativeAndRelativePaths(string? root, string? relativePath) { if (RoslynString.IsNullOrEmpty(root)) { return null; } switch (GetPathKind(relativePath)) { case PathKind.Empty: return root; case PathKind.Absolute: case PathKind.RelativeToCurrentRoot: case PathKind.RelativeToDriveDirectory: return null; } return CombinePathsUnchecked(root, relativePath); } public static string CombinePathsUnchecked(string root, string? relativePath) { RoslynDebug.Assert(!RoslynString.IsNullOrEmpty(root)); char c = root[root.Length - 1]; if (!IsDirectorySeparator(c) && c != VolumeSeparatorChar) { return root + DirectorySeparatorStr + relativePath; } return root + relativePath; } /// <summary> /// Combines paths with the same semantics as <see cref="Path.Combine(string, string)"/> /// but does not throw on null paths or paths with invalid characters. /// </summary> /// <param name="root">First path: absolute, relative, or null.</param> /// <param name="path">Second path: absolute, relative, or null.</param> /// <returns> /// The combined paths. If <paramref name="path"/> contains an absolute path, returns <paramref name="path"/>. /// </returns> /// <remarks> /// Relative and absolute paths treated the same as <see cref="Path.Combine(string, string)"/>. /// </remarks> [return: NotNullIfNotNull("path")] public static string? CombinePaths(string? root, string? path) { if (RoslynString.IsNullOrEmpty(root)) { return path; } if (RoslynString.IsNullOrEmpty(path)) { return root; } return IsAbsolute(path) ? path : CombinePathsUnchecked(root, path); } private static string RemoveTrailingDirectorySeparator(string path) { if (path.Length > 0 && IsDirectorySeparator(path[path.Length - 1])) { return path.Substring(0, path.Length - 1); } else { return path; } } /// <summary> /// Determines whether an assembly reference is considered an assembly file path or an assembly name. /// used, for example, on values of /r and #r. /// </summary> public static bool IsFilePath(string assemblyDisplayNameOrPath) { RoslynDebug.Assert(assemblyDisplayNameOrPath != null); string? extension = FileNameUtilities.GetExtension(assemblyDisplayNameOrPath); return string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".exe", StringComparison.OrdinalIgnoreCase) || assemblyDisplayNameOrPath.IndexOf(DirectorySeparatorChar) != -1 || assemblyDisplayNameOrPath.IndexOf(AltDirectorySeparatorChar) != -1; } /// <summary> /// Determines if "path" contains 'component' within itself. /// i.e. asking if the path "c:\goo\bar\baz" has component "bar" would return 'true'. /// On the other hand, if you had "c:\goo\bar1\baz" then it would not have "bar" as a /// component. /// /// A path contains a component if any file name or directory name in the path /// matches 'component'. As such, if you had something like "\\goo" then that would /// not have "goo" as a component. That's because here "goo" is the server name portion /// of the UNC path, and not an actual directory or file name. /// </summary> public static bool ContainsPathComponent(string? path, string component, bool ignoreCase) { var comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; if (path?.IndexOf(component, comparison) >= 0) { var comparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; int count = 0; string? currentPath = path; while (currentPath != null) { var currentName = GetFileName(currentPath); if (comparer.Equals(currentName, component)) { return true; } currentPath = GetDirectoryName(currentPath); count++; } } return false; } /// <summary> /// Gets a path relative to a directory. /// </summary> public static string GetRelativePath(string directory, string fullPath) { string relativePath = string.Empty; directory = TrimTrailingSeparators(directory); fullPath = TrimTrailingSeparators(fullPath); if (IsChildPath(directory, fullPath)) { return GetRelativeChildPath(directory, fullPath); } var directoryPathParts = GetPathParts(directory); var fullPathParts = GetPathParts(fullPath); if (directoryPathParts.Length == 0 || fullPathParts.Length == 0) { return fullPath; } int index = 0; // find index where full path diverges from base path for (; index < directoryPathParts.Length; index++) { if (!PathsEqual(directoryPathParts[index], fullPathParts[index])) { break; } } // if the first part doesn't match, they don't even have the same volume // so there can be no relative path. if (index == 0) { return fullPath; } // add backup notation for remaining base path levels beyond the index var remainingParts = directoryPathParts.Length - index; if (remainingParts > 0) { for (int i = 0; i < remainingParts; i++) { relativePath = relativePath + ParentRelativeDirectory + DirectorySeparatorStr; } } // add the rest of the full path parts for (int i = index; i < fullPathParts.Length; i++) { relativePath = CombinePathsUnchecked(relativePath, fullPathParts[i]); } return relativePath; } /// <summary> /// True if the child path is a child of the parent path. /// </summary> public static bool IsChildPath(string parentPath, string childPath) { return parentPath.Length > 0 && childPath.Length > parentPath.Length && PathsEqual(childPath, parentPath, parentPath.Length) && (IsDirectorySeparator(parentPath[parentPath.Length - 1]) || IsDirectorySeparator(childPath[parentPath.Length])); } private static string GetRelativeChildPath(string parentPath, string childPath) { var relativePath = childPath.Substring(parentPath.Length); // trim any leading separators left over after removing leading directory int start = ConsumeDirectorySeparators(relativePath, relativePath.Length, 0); if (start > 0) { relativePath = relativePath.Substring(start); } return relativePath; } private static readonly char[] s_pathChars = new char[] { VolumeSeparatorChar, DirectorySeparatorChar, AltDirectorySeparatorChar }; private static string[] GetPathParts(string path) { var pathParts = path.Split(s_pathChars); // remove references to self directories ('.') if (pathParts.Contains(ThisDirectory)) { pathParts = pathParts.Where(s => s != ThisDirectory).ToArray(); } return pathParts; } /// <summary> /// True if the two paths are the same. /// </summary> public static bool PathsEqual(string path1, string path2) { return PathsEqual(path1, path2, Math.Max(path1.Length, path2.Length)); } /// <summary> /// True if the two paths are the same. (but only up to the specified length) /// </summary> private static bool PathsEqual(string path1, string path2, int length) { if (path1.Length < length || path2.Length < length) { return false; } for (int i = 0; i < length; i++) { if (!PathCharEqual(path1[i], path2[i])) { return false; } } return true; } private static bool PathCharEqual(char x, char y) { if (IsDirectorySeparator(x) && IsDirectorySeparator(y)) { return true; } return IsUnixLikePlatform ? x == y : char.ToUpperInvariant(x) == char.ToUpperInvariant(y); } private static int PathHashCode(string? path) { int hc = 0; if (path != null) { foreach (var ch in path) { if (!IsDirectorySeparator(ch)) { hc = Hash.Combine(char.ToUpperInvariant(ch), hc); } } } return hc; } public static string NormalizePathPrefix(string filePath, ImmutableArray<KeyValuePair<string, string>> pathMap) { if (pathMap.IsDefaultOrEmpty) { return filePath; } // find the first key in the path map that matches a prefix of the normalized path. // Note that we expect the client to use consistent capitalization; we use ordinal (case-sensitive) comparisons. foreach (var kv in pathMap) { var oldPrefix = kv.Key; if (!(oldPrefix?.Length > 0)) continue; // oldPrefix always ends with a path separator, so there's no need to check if it was a partial match // e.g. for the map /goo=/bar and filename /goooo if (filePath.StartsWith(oldPrefix, StringComparison.Ordinal)) { var replacementPrefix = kv.Value; // Replace that prefix. var replacement = replacementPrefix + filePath.Substring(oldPrefix.Length); // Normalize the path separators if used uniformly in the replacement bool hasSlash = replacementPrefix.IndexOf('/') >= 0; bool hasBackslash = replacementPrefix.IndexOf('\\') >= 0; return (hasSlash && !hasBackslash) ? replacement.Replace('\\', '/') : (hasBackslash && !hasSlash) ? replacement.Replace('/', '\\') : replacement; } } return filePath; } /// <summary> /// Unfortunately, we cannot depend on Path.GetInvalidPathChars() or Path.GetInvalidFileNameChars() /// From MSDN: The array returned from this method is not guaranteed to contain the complete set of characters /// that are invalid in file and directory names. The full set of invalid characters can vary by file system. /// https://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx /// /// Additionally, Path.GetInvalidPathChars() doesn't include "?" or "*" which are invalid characters, /// and Path.GetInvalidFileNameChars() includes ":" and "\" which are valid characters. /// /// The more accurate way is to let the framework parse the path and throw on any errors. /// </summary> public static bool IsValidFilePath([NotNullWhen(true)] string? fullPath) { try { if (RoslynString.IsNullOrEmpty(fullPath)) { return false; } // Uncomment when this is fixed: https://github.com/dotnet/roslyn/issues/19592 // Debug.Assert(IsAbsolute(fullPath)); var fileInfo = new FileInfo(fullPath); return !string.IsNullOrEmpty(fileInfo.Name); } catch (Exception ex) when ( ex is ArgumentException || // The file name is empty, contains only white spaces, or contains invalid characters. ex is PathTooLongException || // The specified path, file name, or both exceed the system-defined maximum length. ex is NotSupportedException) // fileName contains a colon (:) in the middle of the string. { return false; } } /// <summary> /// If the current environment uses the '\' directory separator, replaces all uses of '\' /// in the given string with '/'. Otherwise, returns the string. /// </summary> /// <remarks> /// This method is equivalent to Microsoft.CodeAnalysis.BuildTasks.GenerateMSBuildEditorConfig.NormalizeWithForwardSlash /// Both methods should be kept in sync. /// </remarks> public static string NormalizeWithForwardSlash(string p) => DirectorySeparatorChar == '/' ? p : p.Replace(DirectorySeparatorChar, '/'); /// <summary> /// Takes an absolute path and attempts to expand any '..' or '.' into their equivalent representation. /// </summary> /// <returns>An equivalent path that does not contain any '..' or '.' path parts, or the original path.</returns> /// <remarks> /// This method handles unix and windows drive rooted absolute paths only (i.e /a/b or x:\a\b). Passing any other kind of path /// including relative, drive relative, unc, or windows device paths will simply return the original input. /// </remarks> public static string ExpandAbsolutePathWithRelativeParts(string p) { bool isDriveRooted = !IsUnixLikePlatform && IsDriveRootedAbsolutePath(p); if (!isDriveRooted && !(p.Length > 1 && p[0] == AltDirectorySeparatorChar)) { // if this isn't a regular absolute path we can't expand it correctly return p; } // GetPathParts also removes any instances of '.' var parts = GetPathParts(p); // For drive rooted paths we need to skip the volume specifier, but remember it for re-joining later var volumeSpecifier = isDriveRooted ? p.Substring(0, 2) : string.Empty; // Skip the root directory var toSkip = isDriveRooted ? 2 : 1; Debug.Assert(parts[toSkip - 1] == string.Empty); var resolvedParts = ArrayBuilder<string>.GetInstance(); foreach (var part in parts.Skip(toSkip)) { if (!part.Equals(ParentRelativeDirectory)) { resolvedParts.Push(part); } // /../../file is considered equal to /file, so we only process the parent relative directory info if there is actually a parent else if (resolvedParts.Count > 0) { resolvedParts.Pop(); } } var expandedPath = volumeSpecifier + '/' + string.Join("/", resolvedParts); resolvedParts.Free(); return expandedPath; } public static readonly IEqualityComparer<string> Comparer = new PathComparer(); private class PathComparer : IEqualityComparer<string?> { public bool Equals(string? x, string? y) { if (x == null && y == null) { return true; } if (x == null || y == null) { return false; } return PathsEqual(x, y); } public int GetHashCode(string? s) { return PathHashCode(s); } } internal static class TestAccessor { internal static string? GetDirectoryName(string path, bool isUnixLike) => PathUtilities.GetDirectoryName(path, isUnixLike); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/CSharp/Portable/SplitOrMergeIfStatements/CSharpSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.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 Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.SplitOrMergeIfStatements; namespace Microsoft.CodeAnalysis.CSharp.SplitOrMergeIfStatements { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.SplitIntoConsecutiveIfStatements), Shared] [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.InvertLogical, Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] internal sealed class CSharpSplitIntoConsecutiveIfStatementsCodeRefactoringProvider : AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpSplitIntoConsecutiveIfStatementsCodeRefactoringProvider() { } } }
// 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 Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.SplitOrMergeIfStatements; namespace Microsoft.CodeAnalysis.CSharp.SplitOrMergeIfStatements { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.SplitIntoConsecutiveIfStatements), Shared] [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.InvertLogical, Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] internal sealed class CSharpSplitIntoConsecutiveIfStatementsCodeRefactoringProvider : AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpSplitIntoConsecutiveIfStatementsCodeRefactoringProvider() { } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/PerLanguageOption2.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; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Marker interface for <see cref="PerLanguageOption2{T}"/> /// </summary> internal interface IPerLanguageOption : IOptionWithGroup { } /// <summary> /// Marker interface for <see cref="PerLanguageOption2{T}"/> /// </summary> internal interface IPerLanguageOption<T> : IPerLanguageOption { } /// <summary> /// An option that can be specified once per language. /// </summary> /// <typeparam name="T"></typeparam> internal partial class PerLanguageOption2<T> : IPerLanguageOption<T> { public OptionDefinition OptionDefinition { get; } /// <inheritdoc cref="OptionDefinition.Feature"/> public string Feature => OptionDefinition.Feature; /// <inheritdoc cref="OptionDefinition.Group"/> internal OptionGroup Group => OptionDefinition.Group; /// <inheritdoc cref="OptionDefinition.Name"/> public string Name => OptionDefinition.Name; /// <inheritdoc cref="OptionDefinition.Type"/> public Type Type => OptionDefinition.Type; /// <inheritdoc cref="OptionDefinition.DefaultValue"/> public T DefaultValue => (T)OptionDefinition.DefaultValue!; /// <summary> /// Storage locations for the option. /// </summary> public ImmutableArray<OptionStorageLocation2> StorageLocations { get; } public PerLanguageOption2(string feature, string name, T defaultValue) : this(feature, name, defaultValue, storageLocations: ImmutableArray<OptionStorageLocation2>.Empty) { } public PerLanguageOption2( string feature, string name, T defaultValue, OptionStorageLocation2 storageLocation) : this(feature, group: OptionGroup.Default, name, defaultValue, ImmutableArray.Create(storageLocation)) { } public PerLanguageOption2( string feature, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2, OptionStorageLocation2 storageLocation3) : this(feature, group: OptionGroup.Default, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2, storageLocation3)) { } public PerLanguageOption2( string feature, string name, T defaultValue, ImmutableArray<OptionStorageLocation2> storageLocations) : this(feature, group: OptionGroup.Default, name, defaultValue, storageLocations) { } internal PerLanguageOption2(string feature, OptionGroup group, string name, T defaultValue) : this(feature, group, name, defaultValue, ImmutableArray<OptionStorageLocation2>.Empty) { } internal PerLanguageOption2( string feature, OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation) : this(feature, group, name, defaultValue, ImmutableArray.Create(storageLocation)) { } internal PerLanguageOption2( string feature, OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2) : this(feature, group, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2)) { } internal PerLanguageOption2( string feature, OptionGroup group, string name, T defaultValue, ImmutableArray<OptionStorageLocation2> storageLocations) { if (string.IsNullOrWhiteSpace(feature)) { throw new ArgumentNullException(nameof(feature)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(nameof(name)); } OptionDefinition = new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: true); this.StorageLocations = storageLocations; } OptionGroup IOptionWithGroup.Group => this.Group; OptionDefinition IOption2.OptionDefinition => OptionDefinition; #if CODE_STYLE object? IOption2.DefaultValue => this.DefaultValue; bool IOption2.IsPerLanguage => true; #else object? IOption.DefaultValue => this.DefaultValue; bool IOption.IsPerLanguage => true; ImmutableArray<OptionStorageLocation> IOption.StorageLocations => this.StorageLocations.As<OptionStorageLocation>(); #endif public override string ToString() => OptionDefinition.ToString(); public override int GetHashCode() => OptionDefinition.GetHashCode(); public override bool Equals(object? obj) => Equals(obj as IOption2); public bool Equals(IOption2? other) { if (ReferenceEquals(this, other)) { return true; } return OptionDefinition == other?.OptionDefinition; } } }
// 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; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Marker interface for <see cref="PerLanguageOption2{T}"/> /// </summary> internal interface IPerLanguageOption : IOptionWithGroup { } /// <summary> /// Marker interface for <see cref="PerLanguageOption2{T}"/> /// </summary> internal interface IPerLanguageOption<T> : IPerLanguageOption { } /// <summary> /// An option that can be specified once per language. /// </summary> /// <typeparam name="T"></typeparam> internal partial class PerLanguageOption2<T> : IPerLanguageOption<T> { public OptionDefinition OptionDefinition { get; } /// <inheritdoc cref="OptionDefinition.Feature"/> public string Feature => OptionDefinition.Feature; /// <inheritdoc cref="OptionDefinition.Group"/> internal OptionGroup Group => OptionDefinition.Group; /// <inheritdoc cref="OptionDefinition.Name"/> public string Name => OptionDefinition.Name; /// <inheritdoc cref="OptionDefinition.Type"/> public Type Type => OptionDefinition.Type; /// <inheritdoc cref="OptionDefinition.DefaultValue"/> public T DefaultValue => (T)OptionDefinition.DefaultValue!; /// <summary> /// Storage locations for the option. /// </summary> public ImmutableArray<OptionStorageLocation2> StorageLocations { get; } public PerLanguageOption2(string feature, string name, T defaultValue) : this(feature, name, defaultValue, storageLocations: ImmutableArray<OptionStorageLocation2>.Empty) { } public PerLanguageOption2( string feature, string name, T defaultValue, OptionStorageLocation2 storageLocation) : this(feature, group: OptionGroup.Default, name, defaultValue, ImmutableArray.Create(storageLocation)) { } public PerLanguageOption2( string feature, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2, OptionStorageLocation2 storageLocation3) : this(feature, group: OptionGroup.Default, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2, storageLocation3)) { } public PerLanguageOption2( string feature, string name, T defaultValue, ImmutableArray<OptionStorageLocation2> storageLocations) : this(feature, group: OptionGroup.Default, name, defaultValue, storageLocations) { } internal PerLanguageOption2(string feature, OptionGroup group, string name, T defaultValue) : this(feature, group, name, defaultValue, ImmutableArray<OptionStorageLocation2>.Empty) { } internal PerLanguageOption2( string feature, OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation) : this(feature, group, name, defaultValue, ImmutableArray.Create(storageLocation)) { } internal PerLanguageOption2( string feature, OptionGroup group, string name, T defaultValue, OptionStorageLocation2 storageLocation1, OptionStorageLocation2 storageLocation2) : this(feature, group, name, defaultValue, ImmutableArray.Create(storageLocation1, storageLocation2)) { } internal PerLanguageOption2( string feature, OptionGroup group, string name, T defaultValue, ImmutableArray<OptionStorageLocation2> storageLocations) { if (string.IsNullOrWhiteSpace(feature)) { throw new ArgumentNullException(nameof(feature)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(nameof(name)); } OptionDefinition = new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: true); this.StorageLocations = storageLocations; } OptionGroup IOptionWithGroup.Group => this.Group; OptionDefinition IOption2.OptionDefinition => OptionDefinition; #if CODE_STYLE object? IOption2.DefaultValue => this.DefaultValue; bool IOption2.IsPerLanguage => true; #else object? IOption.DefaultValue => this.DefaultValue; bool IOption.IsPerLanguage => true; ImmutableArray<OptionStorageLocation> IOption.StorageLocations => this.StorageLocations.As<OptionStorageLocation>(); #endif public override string ToString() => OptionDefinition.ToString(); public override int GetHashCode() => OptionDefinition.GetHashCode(); public override bool Equals(object? obj) => Equals(obj as IOption2); public bool Equals(IOption2? other) { if (ReferenceEquals(this, other)) { return true; } return OptionDefinition == other?.OptionDefinition; } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private readonly SyntaxToken _methodName; private const string NewMethodPascalCaseStr = "NewMethod"; private const string NewMethodCamelCaseStr = "newMethod"; public static Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult, options, localFunction); return codeGenerator.GenerateAsync(cancellationToken); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } throw ExceptionUtilities.UnexpectedValue(selectionResult); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) : base(insertionPoint, selectionResult, analyzerResult, options, localFunction) { Contract.ThrowIfFalse(SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: AnalyzerResult.ReturnType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(), parameters: CreateMethodParameters(), statements: result.Data, methodKind: localFunction ? MethodKind.LocalFunction : MethodKind.Ordinary); return result.With( MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent || CSharpSyntaxFacts.Instance.AreStatementsInSameContainer(firstStatementToRemove, lastStatementToRemove)); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<ImmutableArray<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode) || IsExpressionBodiedAccessor(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false); return ImmutableArray.Create(statement); } // regular case var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements); return statements.CastArray<SyntaxNode>(); } protected override bool ShouldLocalFunctionCaptureParameter(SyntaxNode node) => ((CSharpParseOptions)node.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp8; private static bool IsExpressionBodiedMember(SyntaxNode node) => node is MemberDeclarationSyntax member && member.GetExpressionBody() != null; private static bool IsExpressionBodiedAccessor(SyntaxNode node) => node is AccessorDeclarationSyntax accessor && accessor.ExpressionBody != null; private SimpleNameSyntax CreateMethodNameForInvocation() { return AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = CSharpSelectionResult.ShouldPutAsyncModifier(); var isStatic = !AnalyzerResult.UseInstanceMember; var isReadOnly = AnalyzerResult.ShouldBeReadOnly; // Static local functions are only supported in C# 8.0 and later var languageVersion = ((CSharpParseOptions)SemanticDocument.SyntaxTree.Options).LanguageVersion; if (LocalFunction && (!Options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value || languageVersion < LanguageVersion.CSharp8)) { isStatic = false; } return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: isStatic, isReadOnly: isReadOnly); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<ImmutableArray<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToImmutableArray<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } if (statements.Single() is BlockSyntax block) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private static ImmutableArray<StatementSyntax> CleanupCode(ImmutableArray<StatementSyntax> statements) { statements = PostProcessor.RemoveRedundantBlock(statements); statements = PostProcessor.RemoveDeclarationAssignmentPattern(statements); statements = PostProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private static OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { if (statements.Single() is ReturnStatementSyntax returnStatement && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { if (statement is not LocalDeclarationStatementSyntax declStatement) { return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private ImmutableArray<StatementSyntax> MoveDeclarationOutFromMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { using var _ = ArrayBuilder<StatementSyntax>.GetInstance(out var result); var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); statements = statements.SelectAsArray(s => FixDeclarationExpressionsAndDeclarationPatterns(s, variableToRemoveMap)); foreach (var statement in statements) { if (statement is not LocalDeclarationStatementSyntax declarationStatement || declarationStatement.Declaration.Variables.FullSpan.IsEmpty) { // if given statement is not decl statement. result.Add(statement); continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { var identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token result.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { result.Add(SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList))); triviaList.Clear(); } // return any expression statement if there was any result.AddRange(expressionStatements); } return result.ToImmutable(); } /// <summary> /// If the statement has an <c>out var</c> declaration expression for a variable which /// needs to be removed, we need to turn it into a plain <c>out</c> parameter, so that /// it doesn't declare a duplicate variable. /// If the statement has a pattern declaration (such as <c>3 is int i</c>) for a variable /// which needs to be removed, we will annotate it as a conflict, since we don't have /// a better refactoring. /// </summary> private static StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(StatementSyntax statement, HashSet<SyntaxAnnotation> variablesToRemove) { var replacements = new Dictionary<SyntaxNode, SyntaxNode>(); var declarations = statement.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.DeclarationPattern)); foreach (var node in declarations) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var declaration = (DeclarationExpressionSyntax)node; if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { break; } var designation = (SingleVariableDesignationSyntax)declaration.Designation; var name = designation.Identifier.ValueText; if (variablesToRemove.HasSyntaxAnnotation(designation)) { var newLeadingTrivia = new SyntaxTriviaList(); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetLeadingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia()); replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier) .WithLeadingTrivia(newLeadingTrivia)); } break; } case SyntaxKind.DeclarationPattern: { var pattern = (DeclarationPatternSyntax)node; if (!variablesToRemove.HasSyntaxAnnotation(pattern)) { break; } // We don't have a good refactoring for this, so we just annotate the conflict // For instance, when a local declared by a pattern declaration (`3 is int i`) is // used outside the block we're trying to extract. if (pattern.Designation is not SingleVariableDesignationSyntax designation) { break; } var identifier = designation.Identifier; var annotation = ConflictAnnotation.Create(CSharpFeaturesResources.Conflict_s_detected); var newIdentifier = identifier.WithAdditionalAnnotations(annotation); var newDesignation = designation.WithIdentifier(newIdentifier); replacements.Add(pattern, pattern.WithDesignation(newDesignation)); break; } } } return statement.ReplaceNodes(replacements.Keys, (orig, partiallyReplaced) => replacements[orig]); } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private ImmutableArray<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private static ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) => SyntaxFactory.Identifier(name); protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); var isLocalFunction = LocalFunction && ShouldLocalFunctionCaptureParameter(SemanticDocument.Root); foreach (var argument in AnalyzerResult.MethodParameters) { if (!isLocalFunction || !argument.CanBeCapturedByLocalFunction) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } if (CSharpSelectionResult.ShouldCallConfigureAwaitFalse()) { if (AnalyzerResult.ReturnType.GetMembers().Any(x => x is IMethodSymbol { Name: nameof(Task.ConfigureAwait), Parameters: { Length: 1 } parameters } && parameters[0].Type.SpecialType == SpecialType.System_Boolean)) { invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocation, SyntaxFactory.IdentifierName(nameof(Task.ConfigureAwait))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression))))); } } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) => SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, ExpressionSyntax initialValue, CancellationToken cancellationToken) { var type = variable.GetVariableType(SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<SyntaxNode>(MethodDefinitionAnnotation).First(); #pragma warning disable IDE0007 // Use implicit type (False positive: https://github.com/dotnet/roslyn/issues/44507) SyntaxNode newMethodDefinition = methodDefinition switch #pragma warning restore IDE0007 // Use implicit type { MethodDeclarationSyntax method => TweakNewLinesInMethod(method), LocalFunctionStatementSyntax localFunction => TweakNewLinesInMethod(localFunction), _ => throw new NotSupportedException("SyntaxNode expected to be MethodDeclarationSyntax or LocalFunctionStatementSyntax."), }; newDocument = await newDocument.WithSyntaxRootAsync( root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } private static MethodDeclarationSyntax TweakNewLinesInMethod(MethodDeclarationSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static LocalFunctionStatementSyntax TweakNewLinesInMethod(LocalFunctionStatementSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static TDeclarationNode TweakNewLinesInMethod<TDeclarationNode>(TDeclarationNode method, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody) where TDeclarationNode : SyntaxNode { if (body != null) { return method.ReplaceToken( body.OpenBraceToken, body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else if (expressionBody != null) { return method.ReplaceToken( expressionBody.ArrowToken, expressionBody.ArrowToken.WithPrependedLeadingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else { return method; } } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } protected override async Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) { // Only need to update for nullable reference types in return if (methodSymbolResult.Data.ReturnType.NullableAnnotation != NullableAnnotation.Annotated) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var syntaxNode = originalDocument.Root.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault().AsNode(); var nodeIsMethodOrLocalFunction = syntaxNode is MethodDeclarationSyntax or LocalFunctionStatementSyntax; if (!nodeIsMethodOrLocalFunction) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var nullableReturnOperations = await CheckReturnOperations(syntaxNode, methodSymbolResult, originalDocument, cancellationToken).ConfigureAwait(false); if (nullableReturnOperations is object) { return nullableReturnOperations; } var returnType = syntaxNode is MethodDeclarationSyntax method ? method.ReturnType : ((LocalFunctionStatementSyntax)syntaxNode).ReturnType; var newDocument = await GenerateNewDocument(methodSymbolResult, returnType, originalDocument, cancellationToken).ConfigureAwait(false); return await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); static bool ReturnOperationBelongsToMethod(SyntaxNode returnOperationSyntax, SyntaxNode methodSyntax) { var enclosingMethod = returnOperationSyntax.FirstAncestorOrSelf<SyntaxNode>(n => n switch { BaseMethodDeclarationSyntax _ => true, AnonymousFunctionExpressionSyntax _ => true, LocalFunctionStatementSyntax _ => true, _ => false }); return enclosingMethod == methodSyntax; } async Task<SemanticDocument> CheckReturnOperations( SyntaxNode node, OperationStatus<IMethodSymbol> methodSymbolResult, SemanticDocument originalDocument, CancellationToken cancellationToken) { var semanticModel = originalDocument.SemanticModel; var methodOperation = semanticModel.GetOperation(node, cancellationToken); var returnOperations = methodOperation.DescendantsAndSelf().OfType<IReturnOperation>(); foreach (var returnOperation in returnOperations) { // If the return statement is located in a nested local function or lambda it // shouldn't contribute to the nullability of the extracted method's return type if (!ReturnOperationBelongsToMethod(returnOperation.Syntax, methodOperation.Syntax)) { continue; } var syntax = returnOperation.ReturnedValue?.Syntax ?? returnOperation.Syntax; var returnTypeInfo = semanticModel.GetTypeInfo(syntax, cancellationToken); if (returnTypeInfo.Nullability.FlowState == NullableFlowState.MaybeNull) { // Flow state shows that return is correctly nullable return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } } return null; } static async Task<Document> GenerateNewDocument( OperationStatus<IMethodSymbol> methodSymbolResult, TypeSyntax returnType, SemanticDocument originalDocument, CancellationToken cancellationToken) { // Return type can be updated to not be null var newType = methodSymbolResult.Data.ReturnType.WithNullableAnnotation(NullableAnnotation.NotAnnotated); var oldRoot = await originalDocument.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.ReplaceNode(returnType, newType.GenerateTypeSyntax()); return originalDocument.Document.WithSyntaxRoot(newRoot); } } protected SyntaxToken GenerateMethodNameForStatementGenerators() { var semanticModel = SemanticDocument.SemanticModel; var nameGenerator = new UniqueNameGenerator(semanticModel); var scope = CSharpSelectionResult.GetContainingScope(); // If extracting a local function, we want to ensure all local variables are considered when generating a unique name. if (LocalFunction) { scope = CSharpSelectionResult.GetFirstTokenInSelection().Parent; } return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, GenerateMethodNameFromUserPreference())); } protected string GenerateMethodNameFromUserPreference() { var methodName = NewMethodPascalCaseStr; if (!LocalFunction) { return methodName; } // For local functions, pascal case and camel case should be the most common and therefore we only consider those cases. var namingPreferences = Options.GetOption(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp); var localFunctionPreferences = namingPreferences.SymbolSpecifications.Where(symbol => symbol.AppliesTo(new SymbolKindOrTypeKind(MethodKind.LocalFunction), CreateMethodModifiers(), null)); var namingRules = namingPreferences.Rules.NamingRules; var localFunctionKind = new SymbolKindOrTypeKind(MethodKind.LocalFunction); if (LocalFunction) { if (namingRules.Any(rule => rule.NamingStyle.CapitalizationScheme.Equals(Capitalization.CamelCase) && rule.SymbolSpecification.AppliesTo(localFunctionKind, CreateMethodModifiers(), null))) { methodName = NewMethodCamelCaseStr; } } // We default to pascal case. return methodName; } } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private readonly SyntaxToken _methodName; private const string NewMethodPascalCaseStr = "NewMethod"; private const string NewMethodCamelCaseStr = "newMethod"; public static Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult, options, localFunction); return codeGenerator.GenerateAsync(cancellationToken); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult, options, localFunction); } throw ExceptionUtilities.UnexpectedValue(selectionResult); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options, bool localFunction) : base(insertionPoint, selectionResult, analyzerResult, options, localFunction) { Contract.ThrowIfFalse(SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken) { var result = CreateMethodBody(cancellationToken); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: AnalyzerResult.ReturnType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(), parameters: CreateMethodParameters(), statements: result.Data, methodKind: localFunction ? MethodKind.LocalFunction : MethodKind.Ordinary); return result.With( MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent || CSharpSyntaxFacts.Instance.AreStatementsInSameContainer(firstStatementToRemove, lastStatementToRemove)); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<ImmutableArray<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode) || IsExpressionBodiedAccessor(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false); return ImmutableArray.Create(statement); } // regular case var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = AddSplitOrMoveDeclarationOutStatementsToCallSite(cancellationToken); statements = postProcessor.MergeDeclarationStatements(statements); statements = AddAssignmentStatementToCallSite(statements, cancellationToken); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements); return statements.CastArray<SyntaxNode>(); } protected override bool ShouldLocalFunctionCaptureParameter(SyntaxNode node) => ((CSharpParseOptions)node.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp8; private static bool IsExpressionBodiedMember(SyntaxNode node) => node is MemberDeclarationSyntax member && member.GetExpressionBody() != null; private static bool IsExpressionBodiedAccessor(SyntaxNode node) => node is AccessorDeclarationSyntax accessor && accessor.ExpressionBody != null; private SimpleNameSyntax CreateMethodNameForInvocation() { return AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = CSharpSelectionResult.ShouldPutAsyncModifier(); var isStatic = !AnalyzerResult.UseInstanceMember; var isReadOnly = AnalyzerResult.ShouldBeReadOnly; // Static local functions are only supported in C# 8.0 and later var languageVersion = ((CSharpParseOptions)SemanticDocument.SyntaxTree.Options).LanguageVersion; if (LocalFunction && (!Options.GetOption(CSharpCodeStyleOptions.PreferStaticLocalFunction).Value || languageVersion < LanguageVersion.CSharp8)) { isStatic = false; } return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: isStatic, isReadOnly: isReadOnly); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private OperationStatus<ImmutableArray<SyntaxNode>> CreateMethodBody(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = SplitOrMoveDeclarationIntoMethodDefinition(statements, cancellationToken); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToImmutableArray<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } if (statements.Single() is BlockSyntax block) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private static ImmutableArray<StatementSyntax> CleanupCode(ImmutableArray<StatementSyntax> statements) { statements = PostProcessor.RemoveRedundantBlock(statements); statements = PostProcessor.RemoveDeclarationAssignmentPattern(statements); statements = PostProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private static OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { if (statements.Single() is ReturnStatementSyntax returnStatement && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { if (statement is not LocalDeclarationStatementSyntax declStatement) { return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private ImmutableArray<StatementSyntax> MoveDeclarationOutFromMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { using var _ = ArrayBuilder<StatementSyntax>.GetInstance(out var result); var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); statements = statements.SelectAsArray(s => FixDeclarationExpressionsAndDeclarationPatterns(s, variableToRemoveMap)); foreach (var statement in statements) { if (statement is not LocalDeclarationStatementSyntax declarationStatement || declarationStatement.Declaration.Variables.FullSpan.IsEmpty) { // if given statement is not decl statement. result.Add(statement); continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { var identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token result.Add(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { result.Add(SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList))); triviaList.Clear(); } // return any expression statement if there was any result.AddRange(expressionStatements); } return result.ToImmutable(); } /// <summary> /// If the statement has an <c>out var</c> declaration expression for a variable which /// needs to be removed, we need to turn it into a plain <c>out</c> parameter, so that /// it doesn't declare a duplicate variable. /// If the statement has a pattern declaration (such as <c>3 is int i</c>) for a variable /// which needs to be removed, we will annotate it as a conflict, since we don't have /// a better refactoring. /// </summary> private static StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(StatementSyntax statement, HashSet<SyntaxAnnotation> variablesToRemove) { var replacements = new Dictionary<SyntaxNode, SyntaxNode>(); var declarations = statement.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.DeclarationPattern)); foreach (var node in declarations) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var declaration = (DeclarationExpressionSyntax)node; if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { break; } var designation = (SingleVariableDesignationSyntax)declaration.Designation; var name = designation.Identifier.ValueText; if (variablesToRemove.HasSyntaxAnnotation(designation)) { var newLeadingTrivia = new SyntaxTriviaList(); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetLeadingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia()); replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier) .WithLeadingTrivia(newLeadingTrivia)); } break; } case SyntaxKind.DeclarationPattern: { var pattern = (DeclarationPatternSyntax)node; if (!variablesToRemove.HasSyntaxAnnotation(pattern)) { break; } // We don't have a good refactoring for this, so we just annotate the conflict // For instance, when a local declared by a pattern declaration (`3 is int i`) is // used outside the block we're trying to extract. if (pattern.Designation is not SingleVariableDesignationSyntax designation) { break; } var identifier = designation.Identifier; var annotation = ConflictAnnotation.Create(CSharpFeaturesResources.Conflict_s_detected); var newIdentifier = identifier.WithAdditionalAnnotations(annotation); var newDesignation = designation.WithIdentifier(newIdentifier); replacements.Add(pattern, pattern.WithDesignation(newDesignation)); break; } } } return statement.ReplaceNodes(replacements.Keys, (orig, partiallyReplaced) => replacements[orig]); } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private ImmutableArray<StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( ImmutableArray<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = SemanticDocument.SemanticModel; var context = InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private static ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) => SyntaxFactory.Identifier(name); protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); var isLocalFunction = LocalFunction && ShouldLocalFunctionCaptureParameter(SemanticDocument.Root); foreach (var argument in AnalyzerResult.MethodParameters) { if (!isLocalFunction || !argument.CanBeCapturedByLocalFunction) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } if (CSharpSelectionResult.ShouldCallConfigureAwaitFalse()) { if (AnalyzerResult.ReturnType.GetMembers().Any(x => x is IMethodSymbol { Name: nameof(Task.ConfigureAwait), Parameters: { Length: 1 } parameters } && parameters[0].Type.SpecialType == SpecialType.System_Boolean)) { invocation = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, invocation, SyntaxFactory.IdentifierName(nameof(Task.ConfigureAwait))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression))))); } } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) => SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); protected override StatementSyntax CreateDeclarationStatement( VariableInfo variable, ExpressionSyntax initialValue, CancellationToken cancellationToken) { var type = variable.GetVariableType(SemanticDocument); var typeNode = type.GenerateTypeSyntax(); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<SyntaxNode>(MethodDefinitionAnnotation).First(); #pragma warning disable IDE0007 // Use implicit type (False positive: https://github.com/dotnet/roslyn/issues/44507) SyntaxNode newMethodDefinition = methodDefinition switch #pragma warning restore IDE0007 // Use implicit type { MethodDeclarationSyntax method => TweakNewLinesInMethod(method), LocalFunctionStatementSyntax localFunction => TweakNewLinesInMethod(localFunction), _ => throw new NotSupportedException("SyntaxNode expected to be MethodDeclarationSyntax or LocalFunctionStatementSyntax."), }; newDocument = await newDocument.WithSyntaxRootAsync( root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } private static MethodDeclarationSyntax TweakNewLinesInMethod(MethodDeclarationSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static LocalFunctionStatementSyntax TweakNewLinesInMethod(LocalFunctionStatementSyntax method) => TweakNewLinesInMethod(method, method.Body, method.ExpressionBody); private static TDeclarationNode TweakNewLinesInMethod<TDeclarationNode>(TDeclarationNode method, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody) where TDeclarationNode : SyntaxNode { if (body != null) { return method.ReplaceToken( body.OpenBraceToken, body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else if (expressionBody != null) { return method.ReplaceToken( expressionBody.ArrowToken, expressionBody.ArrowToken.WithPrependedLeadingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.ElasticCarriageReturnLineFeed))); } else { return method; } } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } protected override async Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) { // Only need to update for nullable reference types in return if (methodSymbolResult.Data.ReturnType.NullableAnnotation != NullableAnnotation.Annotated) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var syntaxNode = originalDocument.Root.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault().AsNode(); var nodeIsMethodOrLocalFunction = syntaxNode is MethodDeclarationSyntax or LocalFunctionStatementSyntax; if (!nodeIsMethodOrLocalFunction) { return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } var nullableReturnOperations = await CheckReturnOperations(syntaxNode, methodSymbolResult, originalDocument, cancellationToken).ConfigureAwait(false); if (nullableReturnOperations is object) { return nullableReturnOperations; } var returnType = syntaxNode is MethodDeclarationSyntax method ? method.ReturnType : ((LocalFunctionStatementSyntax)syntaxNode).ReturnType; var newDocument = await GenerateNewDocument(methodSymbolResult, returnType, originalDocument, cancellationToken).ConfigureAwait(false); return await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); static bool ReturnOperationBelongsToMethod(SyntaxNode returnOperationSyntax, SyntaxNode methodSyntax) { var enclosingMethod = returnOperationSyntax.FirstAncestorOrSelf<SyntaxNode>(n => n switch { BaseMethodDeclarationSyntax _ => true, AnonymousFunctionExpressionSyntax _ => true, LocalFunctionStatementSyntax _ => true, _ => false }); return enclosingMethod == methodSyntax; } async Task<SemanticDocument> CheckReturnOperations( SyntaxNode node, OperationStatus<IMethodSymbol> methodSymbolResult, SemanticDocument originalDocument, CancellationToken cancellationToken) { var semanticModel = originalDocument.SemanticModel; var methodOperation = semanticModel.GetOperation(node, cancellationToken); var returnOperations = methodOperation.DescendantsAndSelf().OfType<IReturnOperation>(); foreach (var returnOperation in returnOperations) { // If the return statement is located in a nested local function or lambda it // shouldn't contribute to the nullability of the extracted method's return type if (!ReturnOperationBelongsToMethod(returnOperation.Syntax, methodOperation.Syntax)) { continue; } var syntax = returnOperation.ReturnedValue?.Syntax ?? returnOperation.Syntax; var returnTypeInfo = semanticModel.GetTypeInfo(syntax, cancellationToken); if (returnTypeInfo.Nullability.FlowState == NullableFlowState.MaybeNull) { // Flow state shows that return is correctly nullable return await base.UpdateMethodAfterGenerationAsync(originalDocument, methodSymbolResult, cancellationToken).ConfigureAwait(false); } } return null; } static async Task<Document> GenerateNewDocument( OperationStatus<IMethodSymbol> methodSymbolResult, TypeSyntax returnType, SemanticDocument originalDocument, CancellationToken cancellationToken) { // Return type can be updated to not be null var newType = methodSymbolResult.Data.ReturnType.WithNullableAnnotation(NullableAnnotation.NotAnnotated); var oldRoot = await originalDocument.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.ReplaceNode(returnType, newType.GenerateTypeSyntax()); return originalDocument.Document.WithSyntaxRoot(newRoot); } } protected SyntaxToken GenerateMethodNameForStatementGenerators() { var semanticModel = SemanticDocument.SemanticModel; var nameGenerator = new UniqueNameGenerator(semanticModel); var scope = CSharpSelectionResult.GetContainingScope(); // If extracting a local function, we want to ensure all local variables are considered when generating a unique name. if (LocalFunction) { scope = CSharpSelectionResult.GetFirstTokenInSelection().Parent; } return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(scope, GenerateMethodNameFromUserPreference())); } protected string GenerateMethodNameFromUserPreference() { var methodName = NewMethodPascalCaseStr; if (!LocalFunction) { return methodName; } // For local functions, pascal case and camel case should be the most common and therefore we only consider those cases. var namingPreferences = Options.GetOption(NamingStyleOptions.NamingPreferences, LanguageNames.CSharp); var localFunctionPreferences = namingPreferences.SymbolSpecifications.Where(symbol => symbol.AppliesTo(new SymbolKindOrTypeKind(MethodKind.LocalFunction), CreateMethodModifiers(), null)); var namingRules = namingPreferences.Rules.NamingRules; var localFunctionKind = new SymbolKindOrTypeKind(MethodKind.LocalFunction); if (LocalFunction) { if (namingRules.Any(rule => rule.NamingStyle.CapitalizationScheme.Equals(Capitalization.CamelCase) && rule.SymbolSpecification.AppliesTo(localFunctionKind, CreateMethodModifiers(), null))) { methodName = NewMethodCamelCaseStr; } } // We default to pascal case. return methodName; } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Core/Impl/CodeModel/Collections/NodeSnapshot.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.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { internal class NodeSnapshot : Snapshot { private readonly CodeModelState _state; private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNode _parentNode; private readonly AbstractCodeElement _parentElement; private readonly ImmutableArray<SyntaxNode> _nodes; public NodeSnapshot( CodeModelState state, ComHandle<EnvDTE.FileCodeModel, FileCodeModel> fileCodeModel, SyntaxNode parentNode, AbstractCodeElement parentElement, ImmutableArray<SyntaxNode> nodes) { _state = state; _fileCodeModel = fileCodeModel; _parentNode = parentNode; _parentElement = parentElement; _nodes = nodes; } private ICodeModelService CodeModelService { get { return _state.CodeModelService; } } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node) { this.CodeModelService.GetOptionNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return CodeOptionsStatement.Create(_state, this.FileCodeModel, name, ordinal); } private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node) { var name = this.CodeModelService.GetImportNamespaceOrType(node); return CodeImport.Create(_state, this.FileCodeModel, _parentElement, name); } private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node) { this.CodeModelService.GetAttributeNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return (EnvDTE.CodeElement)CodeAttribute.Create(_state, this.FileCodeModel, _parentElement, name, ordinal); } private EnvDTE.CodeElement CreateCodeParameter(SyntaxNode node) { Debug.Assert(_parentElement is AbstractCodeMember, "Parameters should always have an associated member!"); var name = this.CodeModelService.GetParameterName(node); return (EnvDTE.CodeElement)CodeParameter.Create(_state, (AbstractCodeMember)_parentElement, name); } public override int Count { get { return _nodes.Length; } } public override EnvDTE.CodeElement this[int index] { get { if (index < 0 || index >= _nodes.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } var node = _nodes[index]; if (this.CodeModelService.IsOptionNode(node)) { return CreateCodeOptionsStatement(node); } else if (this.CodeModelService.IsImportNode(node)) { return CreateCodeImport(node); } else if (this.CodeModelService.IsAttributeNode(node)) { return CreateCodeAttribute(node); } else if (this.CodeModelService.IsParameterNode(node)) { return CreateCodeParameter(node); } // The node must be something that the FileCodeModel can create. return this.FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } } } }
// 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.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { internal class NodeSnapshot : Snapshot { private readonly CodeModelState _state; private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNode _parentNode; private readonly AbstractCodeElement _parentElement; private readonly ImmutableArray<SyntaxNode> _nodes; public NodeSnapshot( CodeModelState state, ComHandle<EnvDTE.FileCodeModel, FileCodeModel> fileCodeModel, SyntaxNode parentNode, AbstractCodeElement parentElement, ImmutableArray<SyntaxNode> nodes) { _state = state; _fileCodeModel = fileCodeModel; _parentNode = parentNode; _parentElement = parentElement; _nodes = nodes; } private ICodeModelService CodeModelService { get { return _state.CodeModelService; } } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node) { this.CodeModelService.GetOptionNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return CodeOptionsStatement.Create(_state, this.FileCodeModel, name, ordinal); } private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node) { var name = this.CodeModelService.GetImportNamespaceOrType(node); return CodeImport.Create(_state, this.FileCodeModel, _parentElement, name); } private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node) { this.CodeModelService.GetAttributeNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return (EnvDTE.CodeElement)CodeAttribute.Create(_state, this.FileCodeModel, _parentElement, name, ordinal); } private EnvDTE.CodeElement CreateCodeParameter(SyntaxNode node) { Debug.Assert(_parentElement is AbstractCodeMember, "Parameters should always have an associated member!"); var name = this.CodeModelService.GetParameterName(node); return (EnvDTE.CodeElement)CodeParameter.Create(_state, (AbstractCodeMember)_parentElement, name); } public override int Count { get { return _nodes.Length; } } public override EnvDTE.CodeElement this[int index] { get { if (index < 0 || index >= _nodes.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } var node = _nodes[index]; if (this.CodeModelService.IsOptionNode(node)) { return CreateCodeOptionsStatement(node); } else if (this.CodeModelService.IsImportNode(node)) { return CreateCodeImport(node); } else if (this.CodeModelService.IsAttributeNode(node)) { return CreateCodeAttribute(node); } else if (this.CodeModelService.IsParameterNode(node)) { return CreateCodeParameter(node); } // The node must be something that the FileCodeModel can create. return this.FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ParamKeywordRecommender.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; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ParamKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ParamKeywordRecommender() : base(SyntaxKind.ParamKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var token = context.TargetToken; if (token.Kind() == SyntaxKind.OpenBracketToken && token.Parent.IsKind(SyntaxKind.AttributeList)) { if (token.GetAncestor<PropertyDeclarationSyntax>() != null || token.GetAncestor<EventDeclarationSyntax>() != null) { return true; } } 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.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ParamKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ParamKeywordRecommender() : base(SyntaxKind.ParamKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var token = context.TargetToken; if (token.Kind() == SyntaxKind.OpenBracketToken && token.Parent.IsKind(SyntaxKind.AttributeList)) { if (token.GetAncestor<PropertyDeclarationSyntax>() != null || token.GetAncestor<EventDeclarationSyntax>() != null) { return true; } } return false; } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioIHostWorkspaceProvider.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; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [Shared] [Export(typeof(IHostWorkspaceProvider))] internal sealed class VisualStudioIHostWorkspaceProvider : IHostWorkspaceProvider { public Workspace Workspace { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioIHostWorkspaceProvider(VisualStudioWorkspace workspace) { Workspace = workspace; } } }
// 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; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [Shared] [Export(typeof(IHostWorkspaceProvider))] internal sealed class VisualStudioIHostWorkspaceProvider : IHostWorkspaceProvider { public Workspace Workspace { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioIHostWorkspaceProvider(VisualStudioWorkspace workspace) { Workspace = workspace; } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/LiveShare/Impl/LiveShareConstants.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.LiveShare { internal class LiveShareConstants { // The service name for an LSP server implemented using Roslyn designed to be used with the Roslyn client public const string RoslynContractName = "Roslyn"; // The service name for an LSP server implemented using Roslyn designed to be used with the LSP SDK client public const string RoslynLSPSDKContractName = "RoslynLSPSDK"; public const string TypeScriptLanguageName = "TypeScript"; public const string CSharpContractName = "CSharp"; public const string VisualBasicContractName = "VisualBasic"; public const string TypeScriptContractName = "TypeScript"; } }
// 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.LiveShare { internal class LiveShareConstants { // The service name for an LSP server implemented using Roslyn designed to be used with the Roslyn client public const string RoslynContractName = "Roslyn"; // The service name for an LSP server implemented using Roslyn designed to be used with the LSP SDK client public const string RoslynLSPSDKContractName = "RoslynLSPSDK"; public const string TypeScriptLanguageName = "TypeScript"; public const string CSharpContractName = "CSharp"; public const string VisualBasicContractName = "VisualBasic"; public const string TypeScriptContractName = "TypeScript"; } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/EditorFeatures/CSharpTest/Debugging/NameResolverTests.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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Debugging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging { [UseExportProvider] public class NameResolverTests { private static async Task TestAsync(string text, string searchText, params string[] expectedNames) { using var workspace = TestWorkspace.CreateCSharp(text); var nameResolver = new BreakpointResolver(workspace.CurrentSolution, searchText); var results = await nameResolver.DoAsync(CancellationToken.None); Assert.Equal(expectedNames, results.Select(r => r.LocationNameOpt)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestCSharpLanguageDebugInfoCreateNameResolver() { using var workspace = TestWorkspace.CreateCSharp(" "); var debugInfo = new CSharpBreakpointResolutionService(); var results = await debugInfo.ResolveBreakpointsAsync(workspace.CurrentSolution, "goo", CancellationToken.None); Assert.Equal(0, results.Count()); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestSimpleNameInClass() { var text = @"class C { void Goo() { } }"; await TestAsync(text, "Goo", "C.Goo()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "C.Goo()"); await TestAsync(text, "N.C.Goo"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "C.Goo()"); await TestAsync(text, "Goo(int i)"); await TestAsync(text, "Goo(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestSimpleNameInNamespace() { var text = @" namespace N { class C { void Goo() { } } }"; await TestAsync(text, "Goo", "N.C.Goo()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "N.C.Goo()"); await TestAsync(text, "N.C.Goo", "N.C.Goo()"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "N.C.Goo()"); await TestAsync(text, "C.Goo()", "N.C.Goo()"); await TestAsync(text, "N.C.Goo()", "N.C.Goo()"); await TestAsync(text, "Goo(int i)"); await TestAsync(text, "Goo(int)"); await TestAsync(text, "Goo(a)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestSimpleNameInGenericClassNamespace() { var text = @" namespace N { class C<T> { void Goo() { } } }"; await TestAsync(text, "Goo", "N.C<T>.Goo()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "N.C<T>.Goo()"); await TestAsync(text, "N.C.Goo", "N.C<T>.Goo()"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo", "N.C<T>.Goo()"); await TestAsync(text, "C<T>.Goo()", "N.C<T>.Goo()"); await TestAsync(text, "Goo()", "N.C<T>.Goo()"); await TestAsync(text, "C.Goo()", "N.C<T>.Goo()"); await TestAsync(text, "N.C.Goo()", "N.C<T>.Goo()"); await TestAsync(text, "Goo(int i)"); await TestAsync(text, "Goo(int)"); await TestAsync(text, "Goo(a)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestGenericNameInClassNamespace() { var text = @" namespace N { class C { void Goo<T>() { } } }"; await TestAsync(text, "Goo", "N.C.Goo<T>()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "N.C.Goo<T>()"); await TestAsync(text, "N.C.Goo", "N.C.Goo<T>()"); await TestAsync(text, "Goo<T>", "N.C.Goo<T>()"); await TestAsync(text, "Goo<X>", "N.C.Goo<T>()"); await TestAsync(text, "Goo<T,X>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "C<T>.Goo()"); await TestAsync(text, "Goo()", "N.C.Goo<T>()"); await TestAsync(text, "C.Goo()", "N.C.Goo<T>()"); await TestAsync(text, "N.C.Goo()", "N.C.Goo<T>()"); await TestAsync(text, "Goo(int i)"); await TestAsync(text, "Goo(int)"); await TestAsync(text, "Goo(a)"); await TestAsync(text, "Goo<T>(int i)"); await TestAsync(text, "Goo<T>(int)"); await TestAsync(text, "Goo<T>(a)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestOverloadsInSingleClass() { var text = @"class C { void Goo() { } void Goo(int i) { } }"; await TestAsync(text, "Goo", "C.Goo()", "C.Goo(int)"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "C.Goo()", "C.Goo(int)"); await TestAsync(text, "N.C.Goo"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "C.Goo()"); await TestAsync(text, "Goo(int i)", "C.Goo(int)"); await TestAsync(text, "Goo(int)", "C.Goo(int)"); await TestAsync(text, "Goo(i)", "C.Goo(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestMethodsInMultipleClasses() { var text = @"namespace N { class C { void Goo() { } } } namespace N1 { class C { void Goo(int i) { } } }"; await TestAsync(text, "Goo", "N1.C.Goo(int)", "N.C.Goo()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "N1.C.Goo(int)", "N.C.Goo()"); await TestAsync(text, "N.C.Goo", "N.C.Goo()"); await TestAsync(text, "N1.C.Goo", "N1.C.Goo(int)"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "N.C.Goo()"); await TestAsync(text, "Goo(int i)", "N1.C.Goo(int)"); await TestAsync(text, "Goo(int)", "N1.C.Goo(int)"); await TestAsync(text, "Goo(i)", "N1.C.Goo(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestMethodsWithDifferentArityInMultipleClasses() { var text = @"namespace N { class C { void Goo() { } } } namespace N1 { class C { void Goo<T>(int i) { } } }"; await TestAsync(text, "Goo", "N1.C.Goo<T>(int)", "N.C.Goo()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "N1.C.Goo<T>(int)", "N.C.Goo()"); await TestAsync(text, "N.C.Goo", "N.C.Goo()"); await TestAsync(text, "N1.C.Goo", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo<T>", "N1.C.Goo<T>(int)"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "N.C.Goo()"); await TestAsync(text, "Goo<T>()"); await TestAsync(text, "Goo(int i)", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo(int)", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo(i)", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo<T>(int i)", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo<T>(int)", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo<T>(i)", "N1.C.Goo<T>(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestOverloadsWithMultipleParametersInSingleClass() { var text = @"class C { void Goo(int a) { } void Goo(int a, string b = ""bb"") { } void Goo(__arglist) { } }"; await TestAsync(text, "Goo", "C.Goo(int)", "C.Goo(int, [string])", "C.Goo(__arglist)"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "C.Goo(int)", "C.Goo(int, [string])", "C.Goo(__arglist)"); await TestAsync(text, "N.C.Goo"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "C.Goo(__arglist)"); await TestAsync(text, "Goo(int i)", "C.Goo(int)"); await TestAsync(text, "Goo(int)", "C.Goo(int)"); await TestAsync(text, "Goo(int x = 42)", "C.Goo(int)"); await TestAsync(text, "Goo(i)", "C.Goo(int)"); await TestAsync(text, "Goo(int i, int b)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(int, bool)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(i, s)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(,)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(int x = 42,)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(int x = 42, y = 42)", "C.Goo(int, [string])"); await TestAsync(text, "Goo([attr] x = 42, y = 42)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(int i, int b, char c)"); await TestAsync(text, "Goo(int, bool, char)"); await TestAsync(text, "Goo(i, s, c)"); await TestAsync(text, "Goo(__arglist)", "C.Goo(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task AccessorTests() { var text = @"class C { int Property1 { get { return 42; } } int Property2 { set { } } int Property3 { get; set;} }"; await TestAsync(text, "Property1", "C.Property1"); await TestAsync(text, "Property2", "C.Property2"); await TestAsync(text, "Property3", "C.Property3"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task NegativeTests() { var text = @"using System.Runtime.CompilerServices; abstract class C { public abstract void AbstractMethod(int a); int Field; delegate void Delegate(); event Delegate Event; [IndexerName(""ABCD"")] int this[int i] { get { return i; } } void Goo() { } void Goo(int x = 1, int y = 2) { } ~C() { } }"; await TestAsync(text, "AbstractMethod"); await TestAsync(text, "Field"); await TestAsync(text, "Delegate"); await TestAsync(text, "Event"); await TestAsync(text, "this"); await TestAsync(text, "C.this[int]"); await TestAsync(text, "C.get_Item"); await TestAsync(text, "C.get_Item(i)"); await TestAsync(text, "C[i]"); await TestAsync(text, "ABCD"); await TestAsync(text, "C.ABCD(int)"); await TestAsync(text, "42"); await TestAsync(text, "Goo", "C.Goo()", "C.Goo([int], [int])"); // just making sure it would normally resolve before trying bad syntax await TestAsync(text, "Goo Goo"); await TestAsync(text, "Goo()asdf"); await TestAsync(text, "Goo(),"); await TestAsync(text, "Goo(),f"); await TestAsync(text, "Goo().Goo"); await TestAsync(text, "Goo("); await TestAsync(text, "(Goo"); await TestAsync(text, "Goo)"); await TestAsync(text, "(Goo)"); await TestAsync(text, "Goo(x = 42, y = 42)", "C.Goo([int], [int])"); // just making sure it would normally resolve before trying bad syntax await TestAsync(text, "int x = 42"); await TestAsync(text, "Goo(int x = 42, y = 42"); await TestAsync(text, "C"); await TestAsync(text, "C.C"); await TestAsync(text, "~"); await TestAsync(text, "~C"); await TestAsync(text, "C.~C()"); await TestAsync(text, ""); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestInstanceConstructors() { var text = @"class C { public C() { } } class G<T> { public G() { } ~G() { } }"; await TestAsync(text, "C", "C.C()"); await TestAsync(text, "C.C", "C.C()"); await TestAsync(text, "C.C()", "C.C()"); await TestAsync(text, "C()", "C.C()"); await TestAsync(text, "C<T>"); await TestAsync(text, "C<T>()"); await TestAsync(text, "C(int i)"); await TestAsync(text, "C(int)"); await TestAsync(text, "C(i)"); await TestAsync(text, "G", "G<T>.G()"); await TestAsync(text, "G()", "G<T>.G()"); await TestAsync(text, "G.G", "G<T>.G()"); await TestAsync(text, "G.G()", "G<T>.G()"); await TestAsync(text, "G<T>.G", "G<T>.G()"); await TestAsync(text, "G<t>.G()", "G<T>.G()"); await TestAsync(text, "G<T>"); await TestAsync(text, "G<T>()"); await TestAsync(text, "G.G<T>"); await TestAsync(text, ".ctor"); await TestAsync(text, ".ctor()"); await TestAsync(text, "C.ctor"); await TestAsync(text, "C.ctor()"); await TestAsync(text, "G.ctor"); await TestAsync(text, "G<T>.ctor()"); await TestAsync(text, "Finalize", "G<T>.~G()"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestStaticConstructors() { var text = @"class C { static C() { } }"; await TestAsync(text, "C", "C.C()"); await TestAsync(text, "C.C", "C.C()"); await TestAsync(text, "C.C()", "C.C()"); await TestAsync(text, "C()", "C.C()"); await TestAsync(text, "C<T>"); await TestAsync(text, "C<T>()"); await TestAsync(text, "C(int i)"); await TestAsync(text, "C(int)"); await TestAsync(text, "C(i)"); await TestAsync(text, "C.cctor"); await TestAsync(text, "C.cctor()"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestAllConstructors() { var text = @"class C { static C() { } public C(int i) { } }"; await TestAsync(text, "C", "C.C(int)", "C.C()"); await TestAsync(text, "C.C", "C.C(int)", "C.C()"); await TestAsync(text, "C.C()", "C.C()"); await TestAsync(text, "C()", "C.C()"); await TestAsync(text, "C<T>"); await TestAsync(text, "C<T>()"); await TestAsync(text, "C(int i)", "C.C(int)"); await TestAsync(text, "C(int)", "C.C(int)"); await TestAsync(text, "C(i)", "C.C(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestPartialMethods() { var text = @"partial class C { partial int M1(); partial void M2() { } partial void M2(); partial int M3(); partial int M3(int x) { return 0; } partial void M4() { } }"; await TestAsync(text, "M1"); await TestAsync(text, "C.M1"); await TestAsync(text, "M2", "C.M2()"); await TestAsync(text, "M3", "C.M3(int)"); await TestAsync(text, "M3()"); await TestAsync(text, "M3(y)", "C.M3(int)"); await TestAsync(text, "M4", "C.M4()"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestLeadingAndTrailingText() { var text = @"class C { void Goo() { }; }"; await TestAsync(text, "Goo;", "C.Goo()"); await TestAsync(text, @"Goo();", "C.Goo()"); await TestAsync(text, " Goo;", "C.Goo()"); await TestAsync(text, " Goo;;"); await TestAsync(text, " Goo; ;"); await TestAsync(text, @"Goo();", "C.Goo()"); await TestAsync(text, @"Goo();", "C.Goo()"); await TestAsync(text, @"Goo(); // comment", "C.Goo()"); await TestAsync(text, @"/*comment*/ Goo(/* params */); /* comment", "C.Goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestEscapedKeywords() { var text = @"struct @true { } class @foreach { void where(@true @this) { } void @false() { } }"; await TestAsync(text, "where", "@foreach.where(@true)"); await TestAsync(text, "@where", "@foreach.where(@true)"); await TestAsync(text, "@foreach.where", "@foreach.where(@true)"); await TestAsync(text, "foreach.where"); await TestAsync(text, "@foreach.where(true)"); await TestAsync(text, "@foreach.where(@if)", "@foreach.where(@true)"); await TestAsync(text, "false"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestAliasQualifiedNames() { var text = @"extern alias A class C { void Goo(D d) { } }"; await TestAsync(text, "A::Goo"); await TestAsync(text, "A::Goo(A::B)"); await TestAsync(text, "A::Goo(A::B)"); await TestAsync(text, "A::C.Goo"); await TestAsync(text, "C.Goo(A::Q)", "C.Goo(D)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestNestedTypesAndNamespaces() { var text = @"namespace N1 { class C { void Goo() { } } namespace N2 { class C { } } namespace N3 { class D { } } namespace N4 { class C { void Goo(double x) { } class D { void Goo() { } class E { void Goo() { } } } } } namespace N5 { } }"; await TestAsync(text, "Goo", "N1.N4.C.Goo(double)", "N1.N4.C.D.Goo()", "N1.N4.C.D.E.Goo()", "N1.C.Goo()"); await TestAsync(text, "C.Goo", "N1.N4.C.Goo(double)", "N1.C.Goo()"); await TestAsync(text, "D.Goo", "N1.N4.C.D.Goo()"); await TestAsync(text, "N1.N4.C.D.Goo", "N1.N4.C.D.Goo()"); await TestAsync(text, "N1.Goo"); await TestAsync(text, "N3.C.Goo"); await TestAsync(text, "N5.C.Goo"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestInterfaces() { var text = @"interface I1 { void Goo(); } class C1 : I1 { void I1.Goo() { } }"; await TestAsync(text, "Goo", "C1.Goo()"); await TestAsync(text, "I1.Goo"); await TestAsync(text, "C1.Goo", "C1.Goo()"); await TestAsync(text, "C1.I1.Moo"); } } }
// 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Debugging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging { [UseExportProvider] public class NameResolverTests { private static async Task TestAsync(string text, string searchText, params string[] expectedNames) { using var workspace = TestWorkspace.CreateCSharp(text); var nameResolver = new BreakpointResolver(workspace.CurrentSolution, searchText); var results = await nameResolver.DoAsync(CancellationToken.None); Assert.Equal(expectedNames, results.Select(r => r.LocationNameOpt)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestCSharpLanguageDebugInfoCreateNameResolver() { using var workspace = TestWorkspace.CreateCSharp(" "); var debugInfo = new CSharpBreakpointResolutionService(); var results = await debugInfo.ResolveBreakpointsAsync(workspace.CurrentSolution, "goo", CancellationToken.None); Assert.Equal(0, results.Count()); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestSimpleNameInClass() { var text = @"class C { void Goo() { } }"; await TestAsync(text, "Goo", "C.Goo()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "C.Goo()"); await TestAsync(text, "N.C.Goo"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "C.Goo()"); await TestAsync(text, "Goo(int i)"); await TestAsync(text, "Goo(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestSimpleNameInNamespace() { var text = @" namespace N { class C { void Goo() { } } }"; await TestAsync(text, "Goo", "N.C.Goo()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "N.C.Goo()"); await TestAsync(text, "N.C.Goo", "N.C.Goo()"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "N.C.Goo()"); await TestAsync(text, "C.Goo()", "N.C.Goo()"); await TestAsync(text, "N.C.Goo()", "N.C.Goo()"); await TestAsync(text, "Goo(int i)"); await TestAsync(text, "Goo(int)"); await TestAsync(text, "Goo(a)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestSimpleNameInGenericClassNamespace() { var text = @" namespace N { class C<T> { void Goo() { } } }"; await TestAsync(text, "Goo", "N.C<T>.Goo()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "N.C<T>.Goo()"); await TestAsync(text, "N.C.Goo", "N.C<T>.Goo()"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo", "N.C<T>.Goo()"); await TestAsync(text, "C<T>.Goo()", "N.C<T>.Goo()"); await TestAsync(text, "Goo()", "N.C<T>.Goo()"); await TestAsync(text, "C.Goo()", "N.C<T>.Goo()"); await TestAsync(text, "N.C.Goo()", "N.C<T>.Goo()"); await TestAsync(text, "Goo(int i)"); await TestAsync(text, "Goo(int)"); await TestAsync(text, "Goo(a)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestGenericNameInClassNamespace() { var text = @" namespace N { class C { void Goo<T>() { } } }"; await TestAsync(text, "Goo", "N.C.Goo<T>()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "N.C.Goo<T>()"); await TestAsync(text, "N.C.Goo", "N.C.Goo<T>()"); await TestAsync(text, "Goo<T>", "N.C.Goo<T>()"); await TestAsync(text, "Goo<X>", "N.C.Goo<T>()"); await TestAsync(text, "Goo<T,X>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "C<T>.Goo()"); await TestAsync(text, "Goo()", "N.C.Goo<T>()"); await TestAsync(text, "C.Goo()", "N.C.Goo<T>()"); await TestAsync(text, "N.C.Goo()", "N.C.Goo<T>()"); await TestAsync(text, "Goo(int i)"); await TestAsync(text, "Goo(int)"); await TestAsync(text, "Goo(a)"); await TestAsync(text, "Goo<T>(int i)"); await TestAsync(text, "Goo<T>(int)"); await TestAsync(text, "Goo<T>(a)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestOverloadsInSingleClass() { var text = @"class C { void Goo() { } void Goo(int i) { } }"; await TestAsync(text, "Goo", "C.Goo()", "C.Goo(int)"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "C.Goo()", "C.Goo(int)"); await TestAsync(text, "N.C.Goo"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "C.Goo()"); await TestAsync(text, "Goo(int i)", "C.Goo(int)"); await TestAsync(text, "Goo(int)", "C.Goo(int)"); await TestAsync(text, "Goo(i)", "C.Goo(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestMethodsInMultipleClasses() { var text = @"namespace N { class C { void Goo() { } } } namespace N1 { class C { void Goo(int i) { } } }"; await TestAsync(text, "Goo", "N1.C.Goo(int)", "N.C.Goo()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "N1.C.Goo(int)", "N.C.Goo()"); await TestAsync(text, "N.C.Goo", "N.C.Goo()"); await TestAsync(text, "N1.C.Goo", "N1.C.Goo(int)"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "N.C.Goo()"); await TestAsync(text, "Goo(int i)", "N1.C.Goo(int)"); await TestAsync(text, "Goo(int)", "N1.C.Goo(int)"); await TestAsync(text, "Goo(i)", "N1.C.Goo(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestMethodsWithDifferentArityInMultipleClasses() { var text = @"namespace N { class C { void Goo() { } } } namespace N1 { class C { void Goo<T>(int i) { } } }"; await TestAsync(text, "Goo", "N1.C.Goo<T>(int)", "N.C.Goo()"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "N1.C.Goo<T>(int)", "N.C.Goo()"); await TestAsync(text, "N.C.Goo", "N.C.Goo()"); await TestAsync(text, "N1.C.Goo", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo<T>", "N1.C.Goo<T>(int)"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "N.C.Goo()"); await TestAsync(text, "Goo<T>()"); await TestAsync(text, "Goo(int i)", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo(int)", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo(i)", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo<T>(int i)", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo<T>(int)", "N1.C.Goo<T>(int)"); await TestAsync(text, "Goo<T>(i)", "N1.C.Goo<T>(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestOverloadsWithMultipleParametersInSingleClass() { var text = @"class C { void Goo(int a) { } void Goo(int a, string b = ""bb"") { } void Goo(__arglist) { } }"; await TestAsync(text, "Goo", "C.Goo(int)", "C.Goo(int, [string])", "C.Goo(__arglist)"); await TestAsync(text, "goo"); await TestAsync(text, "C.Goo", "C.Goo(int)", "C.Goo(int, [string])", "C.Goo(__arglist)"); await TestAsync(text, "N.C.Goo"); await TestAsync(text, "Goo<T>"); await TestAsync(text, "C<T>.Goo"); await TestAsync(text, "Goo()", "C.Goo(__arglist)"); await TestAsync(text, "Goo(int i)", "C.Goo(int)"); await TestAsync(text, "Goo(int)", "C.Goo(int)"); await TestAsync(text, "Goo(int x = 42)", "C.Goo(int)"); await TestAsync(text, "Goo(i)", "C.Goo(int)"); await TestAsync(text, "Goo(int i, int b)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(int, bool)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(i, s)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(,)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(int x = 42,)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(int x = 42, y = 42)", "C.Goo(int, [string])"); await TestAsync(text, "Goo([attr] x = 42, y = 42)", "C.Goo(int, [string])"); await TestAsync(text, "Goo(int i, int b, char c)"); await TestAsync(text, "Goo(int, bool, char)"); await TestAsync(text, "Goo(i, s, c)"); await TestAsync(text, "Goo(__arglist)", "C.Goo(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task AccessorTests() { var text = @"class C { int Property1 { get { return 42; } } int Property2 { set { } } int Property3 { get; set;} }"; await TestAsync(text, "Property1", "C.Property1"); await TestAsync(text, "Property2", "C.Property2"); await TestAsync(text, "Property3", "C.Property3"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task NegativeTests() { var text = @"using System.Runtime.CompilerServices; abstract class C { public abstract void AbstractMethod(int a); int Field; delegate void Delegate(); event Delegate Event; [IndexerName(""ABCD"")] int this[int i] { get { return i; } } void Goo() { } void Goo(int x = 1, int y = 2) { } ~C() { } }"; await TestAsync(text, "AbstractMethod"); await TestAsync(text, "Field"); await TestAsync(text, "Delegate"); await TestAsync(text, "Event"); await TestAsync(text, "this"); await TestAsync(text, "C.this[int]"); await TestAsync(text, "C.get_Item"); await TestAsync(text, "C.get_Item(i)"); await TestAsync(text, "C[i]"); await TestAsync(text, "ABCD"); await TestAsync(text, "C.ABCD(int)"); await TestAsync(text, "42"); await TestAsync(text, "Goo", "C.Goo()", "C.Goo([int], [int])"); // just making sure it would normally resolve before trying bad syntax await TestAsync(text, "Goo Goo"); await TestAsync(text, "Goo()asdf"); await TestAsync(text, "Goo(),"); await TestAsync(text, "Goo(),f"); await TestAsync(text, "Goo().Goo"); await TestAsync(text, "Goo("); await TestAsync(text, "(Goo"); await TestAsync(text, "Goo)"); await TestAsync(text, "(Goo)"); await TestAsync(text, "Goo(x = 42, y = 42)", "C.Goo([int], [int])"); // just making sure it would normally resolve before trying bad syntax await TestAsync(text, "int x = 42"); await TestAsync(text, "Goo(int x = 42, y = 42"); await TestAsync(text, "C"); await TestAsync(text, "C.C"); await TestAsync(text, "~"); await TestAsync(text, "~C"); await TestAsync(text, "C.~C()"); await TestAsync(text, ""); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestInstanceConstructors() { var text = @"class C { public C() { } } class G<T> { public G() { } ~G() { } }"; await TestAsync(text, "C", "C.C()"); await TestAsync(text, "C.C", "C.C()"); await TestAsync(text, "C.C()", "C.C()"); await TestAsync(text, "C()", "C.C()"); await TestAsync(text, "C<T>"); await TestAsync(text, "C<T>()"); await TestAsync(text, "C(int i)"); await TestAsync(text, "C(int)"); await TestAsync(text, "C(i)"); await TestAsync(text, "G", "G<T>.G()"); await TestAsync(text, "G()", "G<T>.G()"); await TestAsync(text, "G.G", "G<T>.G()"); await TestAsync(text, "G.G()", "G<T>.G()"); await TestAsync(text, "G<T>.G", "G<T>.G()"); await TestAsync(text, "G<t>.G()", "G<T>.G()"); await TestAsync(text, "G<T>"); await TestAsync(text, "G<T>()"); await TestAsync(text, "G.G<T>"); await TestAsync(text, ".ctor"); await TestAsync(text, ".ctor()"); await TestAsync(text, "C.ctor"); await TestAsync(text, "C.ctor()"); await TestAsync(text, "G.ctor"); await TestAsync(text, "G<T>.ctor()"); await TestAsync(text, "Finalize", "G<T>.~G()"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestStaticConstructors() { var text = @"class C { static C() { } }"; await TestAsync(text, "C", "C.C()"); await TestAsync(text, "C.C", "C.C()"); await TestAsync(text, "C.C()", "C.C()"); await TestAsync(text, "C()", "C.C()"); await TestAsync(text, "C<T>"); await TestAsync(text, "C<T>()"); await TestAsync(text, "C(int i)"); await TestAsync(text, "C(int)"); await TestAsync(text, "C(i)"); await TestAsync(text, "C.cctor"); await TestAsync(text, "C.cctor()"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestAllConstructors() { var text = @"class C { static C() { } public C(int i) { } }"; await TestAsync(text, "C", "C.C(int)", "C.C()"); await TestAsync(text, "C.C", "C.C(int)", "C.C()"); await TestAsync(text, "C.C()", "C.C()"); await TestAsync(text, "C()", "C.C()"); await TestAsync(text, "C<T>"); await TestAsync(text, "C<T>()"); await TestAsync(text, "C(int i)", "C.C(int)"); await TestAsync(text, "C(int)", "C.C(int)"); await TestAsync(text, "C(i)", "C.C(int)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestPartialMethods() { var text = @"partial class C { partial int M1(); partial void M2() { } partial void M2(); partial int M3(); partial int M3(int x) { return 0; } partial void M4() { } }"; await TestAsync(text, "M1"); await TestAsync(text, "C.M1"); await TestAsync(text, "M2", "C.M2()"); await TestAsync(text, "M3", "C.M3(int)"); await TestAsync(text, "M3()"); await TestAsync(text, "M3(y)", "C.M3(int)"); await TestAsync(text, "M4", "C.M4()"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestLeadingAndTrailingText() { var text = @"class C { void Goo() { }; }"; await TestAsync(text, "Goo;", "C.Goo()"); await TestAsync(text, @"Goo();", "C.Goo()"); await TestAsync(text, " Goo;", "C.Goo()"); await TestAsync(text, " Goo;;"); await TestAsync(text, " Goo; ;"); await TestAsync(text, @"Goo();", "C.Goo()"); await TestAsync(text, @"Goo();", "C.Goo()"); await TestAsync(text, @"Goo(); // comment", "C.Goo()"); await TestAsync(text, @"/*comment*/ Goo(/* params */); /* comment", "C.Goo()"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestEscapedKeywords() { var text = @"struct @true { } class @foreach { void where(@true @this) { } void @false() { } }"; await TestAsync(text, "where", "@foreach.where(@true)"); await TestAsync(text, "@where", "@foreach.where(@true)"); await TestAsync(text, "@foreach.where", "@foreach.where(@true)"); await TestAsync(text, "foreach.where"); await TestAsync(text, "@foreach.where(true)"); await TestAsync(text, "@foreach.where(@if)", "@foreach.where(@true)"); await TestAsync(text, "false"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestAliasQualifiedNames() { var text = @"extern alias A class C { void Goo(D d) { } }"; await TestAsync(text, "A::Goo"); await TestAsync(text, "A::Goo(A::B)"); await TestAsync(text, "A::Goo(A::B)"); await TestAsync(text, "A::C.Goo"); await TestAsync(text, "C.Goo(A::Q)", "C.Goo(D)"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestNestedTypesAndNamespaces() { var text = @"namespace N1 { class C { void Goo() { } } namespace N2 { class C { } } namespace N3 { class D { } } namespace N4 { class C { void Goo(double x) { } class D { void Goo() { } class E { void Goo() { } } } } } namespace N5 { } }"; await TestAsync(text, "Goo", "N1.N4.C.Goo(double)", "N1.N4.C.D.Goo()", "N1.N4.C.D.E.Goo()", "N1.C.Goo()"); await TestAsync(text, "C.Goo", "N1.N4.C.Goo(double)", "N1.C.Goo()"); await TestAsync(text, "D.Goo", "N1.N4.C.D.Goo()"); await TestAsync(text, "N1.N4.C.D.Goo", "N1.N4.C.D.Goo()"); await TestAsync(text, "N1.Goo"); await TestAsync(text, "N3.C.Goo"); await TestAsync(text, "N5.C.Goo"); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingNameResolver)] public async Task TestInterfaces() { var text = @"interface I1 { void Goo(); } class C1 : I1 { void I1.Goo() { } }"; await TestAsync(text, "Goo", "C1.Goo()"); await TestAsync(text, "I1.Goo"); await TestAsync(text, "C1.Goo", "C1.Goo()"); await TestAsync(text, "C1.I1.Moo"); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/Core/Portable/PdbSourceDocument/PdbSourceDocumentMetadataAsSourceFileProvider.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.Composition; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PdbSourceDocument { [ExportMetadataAsSourceFileProvider(ProviderName), Shared] [ExtensionOrder(Before = DecompilationMetadataAsSourceFileProvider.ProviderName)] internal sealed class PdbSourceDocumentMetadataAsSourceFileProvider : IMetadataAsSourceFileProvider { internal const string ProviderName = "PdbSource"; private readonly IPdbFileLocatorService _pdbFileLocatorService; private readonly IPdbSourceDocumentLoaderService _pdbSourceDocumentLoaderService; private readonly Dictionary<string, ProjectId> _assemblyToProjectMap = new(); private readonly Dictionary<string, (DocumentId documentId, Encoding encoding)> _fileToDocumentMap = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PdbSourceDocumentMetadataAsSourceFileProvider(IPdbFileLocatorService pdbFileLocatorService, IPdbSourceDocumentLoaderService pdbSourceDocumentLoaderService) { _pdbFileLocatorService = pdbFileLocatorService; _pdbSourceDocumentLoaderService = pdbSourceDocumentLoaderService; } public async Task<MetadataAsSourceFile?> GetGeneratedFileAsync(Workspace workspace, Project project, ISymbol symbol, bool signaturesOnly, bool allowDecompilation, string tempPath, CancellationToken cancellationToken) { // we don't support signatures only mode if (signaturesOnly) return null; // If this is a reference assembly then we won't have the right information available, so bail out // TODO: find the implementation assembly for the reference assembly, and keep going: https://github.com/dotnet/roslyn/issues/55834 var isReferenceAssembly = symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass?.Name == nameof(ReferenceAssemblyAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(ReferenceAssemblyAttribute).FullName); if (isReferenceAssembly) return null; var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); if (compilation.GetMetadataReference(symbol.ContainingAssembly) is not PortableExecutableReference { FilePath: not null and var dllPath }) { return null; } var assemblyName = symbol.ContainingAssembly.Identity.Name; ImmutableDictionary<string, string> pdbCompilationOptions; ImmutableArray<SourceDocument> sourceDocuments; // We know we have a DLL, call and see if we can find metadata readers for it, and for the PDB (whereever it may be) using (var documentDebugInfoReader = await _pdbFileLocatorService.GetDocumentDebugInfoReaderAsync(dllPath, cancellationToken).ConfigureAwait(false)) { if (documentDebugInfoReader is null) return null; // If we don't already have a project for this assembly, we'll need to create one, and we want to use // the same compiler options for it that the DLL was created with. We also want to do that early so we // can dispose files sooner pdbCompilationOptions = documentDebugInfoReader.GetCompilationOptions(); // Try to find some actual document information from the PDB sourceDocuments = documentDebugInfoReader.FindSourceDocuments(symbol); if (sourceDocuments.Length == 0) return null; } Encoding? defaultEncoding = null; if (pdbCompilationOptions.TryGetValue("default-encoding", out var encodingString)) { defaultEncoding = Encoding.GetEncoding(encodingString); } else if (pdbCompilationOptions.TryGetValue("fallback-encoding", out var fallbackEncodingString)) { defaultEncoding = Encoding.GetEncoding(fallbackEncodingString); } // Get text loaders for our documents. We do this here because if we can't load any of the files, then // we can't provide any results, so there is no point adding a project to the workspace etc. var textLoaderTasks = sourceDocuments.Select(sd => _pdbSourceDocumentLoaderService.LoadSourceDocumentAsync(sd, defaultEncoding, cancellationToken)).ToArray(); var textLoaders = await Task.WhenAll(textLoaderTasks).ConfigureAwait(false); if (textLoaders.Where(t => t is null).Any()) return null; if (!_assemblyToProjectMap.TryGetValue(assemblyName, out var projectId)) { // Get the project info now, so we can dispose the documentDebugInfoReader sooner var projectInfo = CreateProjectInfo(workspace, project, pdbCompilationOptions, assemblyName); if (projectInfo is null) return null; projectId = projectInfo.Id; workspace.OnProjectAdded(projectInfo); _assemblyToProjectMap.Add(assemblyName, projectId); } var symbolId = SymbolKey.Create(symbol, cancellationToken); var navigateProject = workspace.CurrentSolution.GetRequiredProject(projectId); Contract.ThrowIfFalse(sourceDocuments.Length == textLoaders.Length); // Combine text loaders and file paths. Task.WhenAll ensures order is preserved. var filePathsAndTextLoaders = sourceDocuments.Select((sd, i) => (sd.FilePath, textLoaders[i]!)).ToImmutableArray(); var documentInfos = CreateDocumentInfos(filePathsAndTextLoaders, navigateProject); if (documentInfos.Length > 0) { workspace.OnDocumentsAdded(documentInfos); navigateProject = workspace.CurrentSolution.GetRequiredProject(projectId); } var documentPath = filePathsAndTextLoaders[0].FilePath; var document = navigateProject.Documents.FirstOrDefault(d => d.FilePath?.Equals(documentPath, StringComparison.OrdinalIgnoreCase) ?? false); // TODO: Can we avoid writing a temp file, and convince Visual Studio to open a file that doesn't exist on disk? https://github.com/dotnet/roslyn/issues/55834 var tempFilePath = Path.Combine(tempPath, projectId.Id.ToString(), Path.GetFileName(documentPath)); // We might already know about this file, but lets make sure it still exists too if (!_fileToDocumentMap.ContainsKey(tempFilePath) || !File.Exists(tempFilePath)) { // We have the content, so write it out to disk var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. var directoryToCreate = Path.GetDirectoryName(tempFilePath)!; var loopCount = 0; while (!Directory.Exists(directoryToCreate)) { // Protect against infinite loops. if (loopCount++ > 10) return null; try { Directory.CreateDirectory(directoryToCreate); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { } } var encoding = text.Encoding ?? Encoding.UTF8; using (var textWriter = new StreamWriter(tempFilePath, append: false, encoding: encoding)) { text.Write(textWriter, cancellationToken); } // Mark read-only new FileInfo(tempFilePath).IsReadOnly = true; _fileToDocumentMap[tempFilePath] = (document.Id, encoding); } var navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false); var navigateDocument = navigateProject.GetDocument(navigateLocation.SourceTree); // TODO: "from metadata" is technically correct, but could be confusing. From PDB? From Source? https://github.com/dotnet/roslyn/issues/55834 var documentName = string.Format( "{0} [{1}]", navigateDocument!.Name, FeaturesResources.from_metadata); return new MetadataAsSourceFile(tempFilePath, navigateLocation, documentName, navigateDocument.FilePath); } private static ProjectInfo? CreateProjectInfo(Workspace workspace, Project project, ImmutableDictionary<string, string> pdbCompilationOptions, string assemblyName) { // First we need the language name in order to get the services // TODO: Find language another way for non portable PDBs: https://github.com/dotnet/roslyn/issues/55834 if (!pdbCompilationOptions.TryGetValue("language", out var languageName) || languageName is null) return null; var languageServices = workspace.Services.GetLanguageServices(languageName); // TODO: Use compiler API when available: https://github.com/dotnet/roslyn/issues/57356 var compilationOptions = languageServices.GetRequiredService<ICompilationFactoryService>().TryParsePdbCompilationOptions(pdbCompilationOptions); var parseOptions = languageServices.GetRequiredService<ISyntaxTreeFactoryService>().TryParsePdbParseOptions(pdbCompilationOptions); var projectId = ProjectId.CreateNewId(); return ProjectInfo.Create( projectId, VersionStamp.Default, name: assemblyName + ProviderName, // Distinguish this project from any decompilation projects that might be created assemblyName: assemblyName, language: languageName, compilationOptions: compilationOptions, parseOptions: parseOptions, metadataReferences: project.MetadataReferences.ToImmutableArray()); // TODO: Read references from PDB info: https://github.com/dotnet/roslyn/issues/55834 } private static ImmutableArray<DocumentInfo> CreateDocumentInfos(ImmutableArray<(string FilePath, TextLoader Loader)> filePaths, Project project) { using var _ = ArrayBuilder<DocumentInfo>.GetInstance(out var documents); foreach (var sourceDocument in filePaths) { // If a document has multiple symbols then we would already know about it if (project.Documents.Contains(d => d.FilePath?.Equals(sourceDocument.FilePath, StringComparison.OrdinalIgnoreCase) ?? false)) continue; var documentId = DocumentId.CreateNewId(project.Id); documents.Add(DocumentInfo.Create( documentId, Path.GetFileName(sourceDocument.FilePath), filePath: sourceDocument.FilePath, loader: sourceDocument.Loader)); } return documents.ToImmutable(); } public bool TryAddDocumentToWorkspace(Workspace workspace, string filePath, SourceTextContainer sourceTextContainer) { if (_fileToDocumentMap.TryGetValue(filePath, out var value)) { workspace.OnDocumentOpened(value.documentId, sourceTextContainer); return true; } return false; } public bool TryRemoveDocumentFromWorkspace(Workspace workspace, string filePath) { if (_fileToDocumentMap.TryGetValue(filePath, out var value)) { workspace.OnDocumentClosed(value.documentId, new FileTextLoader(filePath, value.encoding)); return true; } return false; } public Project? MapDocument(Document document) { return document.Project; } public void CleanupGeneratedFiles(Workspace? workspace) { if (workspace is not null) { var projectIds = _assemblyToProjectMap.Values; foreach (var projectId in projectIds) { workspace.OnProjectRemoved(projectId); } } _assemblyToProjectMap.Clear(); // The MetadataAsSourceFileService will clean up the entire temp folder so no need to do anything here _fileToDocumentMap.Clear(); } } internal sealed record SourceDocument(string FilePath, SourceHashAlgorithm HashAlgorithm, ImmutableArray<byte> Checksum, byte[]? EmbeddedTextBytes); }
// 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.Composition; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PdbSourceDocument { [ExportMetadataAsSourceFileProvider(ProviderName), Shared] [ExtensionOrder(Before = DecompilationMetadataAsSourceFileProvider.ProviderName)] internal sealed class PdbSourceDocumentMetadataAsSourceFileProvider : IMetadataAsSourceFileProvider { internal const string ProviderName = "PdbSource"; private readonly IPdbFileLocatorService _pdbFileLocatorService; private readonly IPdbSourceDocumentLoaderService _pdbSourceDocumentLoaderService; private readonly Dictionary<string, ProjectId> _assemblyToProjectMap = new(); private readonly Dictionary<string, (DocumentId documentId, Encoding encoding)> _fileToDocumentMap = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PdbSourceDocumentMetadataAsSourceFileProvider(IPdbFileLocatorService pdbFileLocatorService, IPdbSourceDocumentLoaderService pdbSourceDocumentLoaderService) { _pdbFileLocatorService = pdbFileLocatorService; _pdbSourceDocumentLoaderService = pdbSourceDocumentLoaderService; } public async Task<MetadataAsSourceFile?> GetGeneratedFileAsync(Workspace workspace, Project project, ISymbol symbol, bool signaturesOnly, bool allowDecompilation, string tempPath, CancellationToken cancellationToken) { // we don't support signatures only mode if (signaturesOnly) return null; // If this is a reference assembly then we won't have the right information available, so bail out // TODO: find the implementation assembly for the reference assembly, and keep going: https://github.com/dotnet/roslyn/issues/55834 var isReferenceAssembly = symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass?.Name == nameof(ReferenceAssemblyAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(ReferenceAssemblyAttribute).FullName); if (isReferenceAssembly) return null; var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); if (compilation.GetMetadataReference(symbol.ContainingAssembly) is not PortableExecutableReference { FilePath: not null and var dllPath }) { return null; } var assemblyName = symbol.ContainingAssembly.Identity.Name; ImmutableDictionary<string, string> pdbCompilationOptions; ImmutableArray<SourceDocument> sourceDocuments; // We know we have a DLL, call and see if we can find metadata readers for it, and for the PDB (whereever it may be) using (var documentDebugInfoReader = await _pdbFileLocatorService.GetDocumentDebugInfoReaderAsync(dllPath, cancellationToken).ConfigureAwait(false)) { if (documentDebugInfoReader is null) return null; // If we don't already have a project for this assembly, we'll need to create one, and we want to use // the same compiler options for it that the DLL was created with. We also want to do that early so we // can dispose files sooner pdbCompilationOptions = documentDebugInfoReader.GetCompilationOptions(); // Try to find some actual document information from the PDB sourceDocuments = documentDebugInfoReader.FindSourceDocuments(symbol); if (sourceDocuments.Length == 0) return null; } Encoding? defaultEncoding = null; if (pdbCompilationOptions.TryGetValue("default-encoding", out var encodingString)) { defaultEncoding = Encoding.GetEncoding(encodingString); } else if (pdbCompilationOptions.TryGetValue("fallback-encoding", out var fallbackEncodingString)) { defaultEncoding = Encoding.GetEncoding(fallbackEncodingString); } // Get text loaders for our documents. We do this here because if we can't load any of the files, then // we can't provide any results, so there is no point adding a project to the workspace etc. var textLoaderTasks = sourceDocuments.Select(sd => _pdbSourceDocumentLoaderService.LoadSourceDocumentAsync(sd, defaultEncoding, cancellationToken)).ToArray(); var textLoaders = await Task.WhenAll(textLoaderTasks).ConfigureAwait(false); if (textLoaders.Where(t => t is null).Any()) return null; if (!_assemblyToProjectMap.TryGetValue(assemblyName, out var projectId)) { // Get the project info now, so we can dispose the documentDebugInfoReader sooner var projectInfo = CreateProjectInfo(workspace, project, pdbCompilationOptions, assemblyName); if (projectInfo is null) return null; projectId = projectInfo.Id; workspace.OnProjectAdded(projectInfo); _assemblyToProjectMap.Add(assemblyName, projectId); } var symbolId = SymbolKey.Create(symbol, cancellationToken); var navigateProject = workspace.CurrentSolution.GetRequiredProject(projectId); Contract.ThrowIfFalse(sourceDocuments.Length == textLoaders.Length); // Combine text loaders and file paths. Task.WhenAll ensures order is preserved. var filePathsAndTextLoaders = sourceDocuments.Select((sd, i) => (sd.FilePath, textLoaders[i]!)).ToImmutableArray(); var documentInfos = CreateDocumentInfos(filePathsAndTextLoaders, navigateProject); if (documentInfos.Length > 0) { workspace.OnDocumentsAdded(documentInfos); navigateProject = workspace.CurrentSolution.GetRequiredProject(projectId); } var documentPath = filePathsAndTextLoaders[0].FilePath; var document = navigateProject.Documents.FirstOrDefault(d => d.FilePath?.Equals(documentPath, StringComparison.OrdinalIgnoreCase) ?? false); // TODO: Can we avoid writing a temp file, and convince Visual Studio to open a file that doesn't exist on disk? https://github.com/dotnet/roslyn/issues/55834 var tempFilePath = Path.Combine(tempPath, projectId.Id.ToString(), Path.GetFileName(documentPath)); // We might already know about this file, but lets make sure it still exists too if (!_fileToDocumentMap.ContainsKey(tempFilePath) || !File.Exists(tempFilePath)) { // We have the content, so write it out to disk var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. var directoryToCreate = Path.GetDirectoryName(tempFilePath)!; var loopCount = 0; while (!Directory.Exists(directoryToCreate)) { // Protect against infinite loops. if (loopCount++ > 10) return null; try { Directory.CreateDirectory(directoryToCreate); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { } } var encoding = text.Encoding ?? Encoding.UTF8; using (var textWriter = new StreamWriter(tempFilePath, append: false, encoding: encoding)) { text.Write(textWriter, cancellationToken); } // Mark read-only new FileInfo(tempFilePath).IsReadOnly = true; _fileToDocumentMap[tempFilePath] = (document.Id, encoding); } var navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false); var navigateDocument = navigateProject.GetDocument(navigateLocation.SourceTree); // TODO: "from metadata" is technically correct, but could be confusing. From PDB? From Source? https://github.com/dotnet/roslyn/issues/55834 var documentName = string.Format( "{0} [{1}]", navigateDocument!.Name, FeaturesResources.from_metadata); return new MetadataAsSourceFile(tempFilePath, navigateLocation, documentName, navigateDocument.FilePath); } private static ProjectInfo? CreateProjectInfo(Workspace workspace, Project project, ImmutableDictionary<string, string> pdbCompilationOptions, string assemblyName) { // First we need the language name in order to get the services // TODO: Find language another way for non portable PDBs: https://github.com/dotnet/roslyn/issues/55834 if (!pdbCompilationOptions.TryGetValue("language", out var languageName) || languageName is null) return null; var languageServices = workspace.Services.GetLanguageServices(languageName); // TODO: Use compiler API when available: https://github.com/dotnet/roslyn/issues/57356 var compilationOptions = languageServices.GetRequiredService<ICompilationFactoryService>().TryParsePdbCompilationOptions(pdbCompilationOptions); var parseOptions = languageServices.GetRequiredService<ISyntaxTreeFactoryService>().TryParsePdbParseOptions(pdbCompilationOptions); var projectId = ProjectId.CreateNewId(); return ProjectInfo.Create( projectId, VersionStamp.Default, name: assemblyName + ProviderName, // Distinguish this project from any decompilation projects that might be created assemblyName: assemblyName, language: languageName, compilationOptions: compilationOptions, parseOptions: parseOptions, metadataReferences: project.MetadataReferences.ToImmutableArray()); // TODO: Read references from PDB info: https://github.com/dotnet/roslyn/issues/55834 } private static ImmutableArray<DocumentInfo> CreateDocumentInfos(ImmutableArray<(string FilePath, TextLoader Loader)> filePaths, Project project) { using var _ = ArrayBuilder<DocumentInfo>.GetInstance(out var documents); foreach (var sourceDocument in filePaths) { // If a document has multiple symbols then we would already know about it if (project.Documents.Contains(d => d.FilePath?.Equals(sourceDocument.FilePath, StringComparison.OrdinalIgnoreCase) ?? false)) continue; var documentId = DocumentId.CreateNewId(project.Id); documents.Add(DocumentInfo.Create( documentId, Path.GetFileName(sourceDocument.FilePath), filePath: sourceDocument.FilePath, loader: sourceDocument.Loader)); } return documents.ToImmutable(); } public bool TryAddDocumentToWorkspace(Workspace workspace, string filePath, SourceTextContainer sourceTextContainer) { if (_fileToDocumentMap.TryGetValue(filePath, out var value)) { workspace.OnDocumentOpened(value.documentId, sourceTextContainer); return true; } return false; } public bool TryRemoveDocumentFromWorkspace(Workspace workspace, string filePath) { if (_fileToDocumentMap.TryGetValue(filePath, out var value)) { workspace.OnDocumentClosed(value.documentId, new FileTextLoader(filePath, value.encoding)); return true; } return false; } public Project? MapDocument(Document document) { return document.Project; } public void CleanupGeneratedFiles(Workspace? workspace) { if (workspace is not null) { var projectIds = _assemblyToProjectMap.Values; foreach (var projectId in projectIds) { workspace.OnProjectRemoved(projectId); } } _assemblyToProjectMap.Clear(); // The MetadataAsSourceFileService will clean up the entire temp folder so no need to do anything here _fileToDocumentMap.Clear(); } } internal sealed record SourceDocument(string FilePath, SourceHashAlgorithm HashAlgorithm, ImmutableArray<byte> Checksum, byte[]? EmbeddedTextBytes); }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/CodeAnalysisTest/CommonSyntaxTests.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.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; using CS = Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonSyntaxTests { [Fact] public void Kinds() { foreach (CS.SyntaxKind kind in Enum.GetValues(typeof(CS.SyntaxKind))) { Assert.True(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should be C# kind"); if (kind != CS.SyntaxKind.None && kind != CS.SyntaxKind.List) { Assert.False(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should not be VB kind"); } } foreach (VB.SyntaxKind kind in Enum.GetValues(typeof(VB.SyntaxKind))) { Assert.True(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should be VB kind"); if (kind != VB.SyntaxKind.None && kind != VB.SyntaxKind.List) { Assert.False(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should not be C# kind"); } } } [Fact] public void SyntaxNodeOrToken() { var d = default(SyntaxNodeOrToken); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void SyntaxNodeOrToken1() { var d = (SyntaxNodeOrToken)((SyntaxNode)null); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void CommonSyntaxToString_CSharp() { SyntaxNode node = CSharp.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = CSharp.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxToString_VisualBasic() { SyntaxNode node = VB.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = VB.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxTriviaSpan_CSharp() { var csharpToken = CSharp.SyntaxFactory.ParseExpression("1 + 123 /*hello*/").GetLastToken(); var csharpTriviaList = csharpToken.TrailingTrivia; Assert.Equal(2, csharpTriviaList.Count); var csharpTrivia = csharpTriviaList.ElementAt(1); Assert.Equal(CSharp.SyntaxKind.MultiLineCommentTrivia, CSharp.CSharpExtensions.Kind(csharpTrivia)); var correctSpan = csharpTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(17, correctSpan.End); var commonTrivia = (SyntaxTrivia)csharpTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)csharpTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)csharpToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var csharpTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, csharpTrivia2.Span); var csharpTriviaList2 = (SyntaxTriviaList)commonTriviaList; var csharpTrivia3 = csharpTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, csharpTrivia3.Span); } [Fact] public void CommonSyntaxTriviaSpan_VisualBasic() { var vbToken = VB.SyntaxFactory.ParseExpression("1 + 123 'hello").GetLastToken(); var vbTriviaList = (SyntaxTriviaList)vbToken.TrailingTrivia; Assert.Equal(2, vbTriviaList.Count); var vbTrivia = vbTriviaList.ElementAt(1); Assert.Equal(VB.SyntaxKind.CommentTrivia, VB.VisualBasicExtensions.Kind(vbTrivia)); var correctSpan = vbTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(14, correctSpan.End); var commonTrivia = (SyntaxTrivia)vbTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)vbTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)vbToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var vbTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, vbTrivia2.Span); var vbTriviaList2 = (SyntaxTriviaList)commonTriviaList; var vbTrivia3 = vbTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, vbTrivia3.Span); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void CSharpSyntax_VisualBasicKind() { var node = CSharp.SyntaxFactory.Identifier("a"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(node)); var token = CSharp.SyntaxFactory.Token(CSharp.SyntaxKind.IfKeyword); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(token)); var trivia = CSharp.SyntaxFactory.Comment("c"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(trivia)); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void VisualBasicSyntax_CSharpKind() { var node = VisualBasic.SyntaxFactory.Identifier("a"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(node)); var token = VisualBasic.SyntaxFactory.Token(VisualBasic.SyntaxKind.IfKeyword); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(token)); var trivia = VisualBasic.SyntaxFactory.CommentTrivia("c"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(trivia)); } [Fact] public void TestTrackNodes() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } [Fact] public void TestTrackNodesWithDuplicateIdAnnotations() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); var annotation = trackedExpr.GetAnnotatedNodes(SyntaxNodeExtensions.IdAnnotationKind).First() .GetAnnotations(SyntaxNodeExtensions.IdAnnotationKind).First(); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten).WithAdditionalAnnotations(annotation)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } } }
// 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.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; using CS = Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonSyntaxTests { [Fact] public void Kinds() { foreach (CS.SyntaxKind kind in Enum.GetValues(typeof(CS.SyntaxKind))) { Assert.True(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should be C# kind"); if (kind != CS.SyntaxKind.None && kind != CS.SyntaxKind.List) { Assert.False(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should not be VB kind"); } } foreach (VB.SyntaxKind kind in Enum.GetValues(typeof(VB.SyntaxKind))) { Assert.True(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should be VB kind"); if (kind != VB.SyntaxKind.None && kind != VB.SyntaxKind.List) { Assert.False(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should not be C# kind"); } } } [Fact] public void SyntaxNodeOrToken() { var d = default(SyntaxNodeOrToken); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void SyntaxNodeOrToken1() { var d = (SyntaxNodeOrToken)((SyntaxNode)null); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void CommonSyntaxToString_CSharp() { SyntaxNode node = CSharp.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = CSharp.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxToString_VisualBasic() { SyntaxNode node = VB.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = VB.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxTriviaSpan_CSharp() { var csharpToken = CSharp.SyntaxFactory.ParseExpression("1 + 123 /*hello*/").GetLastToken(); var csharpTriviaList = csharpToken.TrailingTrivia; Assert.Equal(2, csharpTriviaList.Count); var csharpTrivia = csharpTriviaList.ElementAt(1); Assert.Equal(CSharp.SyntaxKind.MultiLineCommentTrivia, CSharp.CSharpExtensions.Kind(csharpTrivia)); var correctSpan = csharpTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(17, correctSpan.End); var commonTrivia = (SyntaxTrivia)csharpTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)csharpTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)csharpToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var csharpTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, csharpTrivia2.Span); var csharpTriviaList2 = (SyntaxTriviaList)commonTriviaList; var csharpTrivia3 = csharpTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, csharpTrivia3.Span); } [Fact] public void CommonSyntaxTriviaSpan_VisualBasic() { var vbToken = VB.SyntaxFactory.ParseExpression("1 + 123 'hello").GetLastToken(); var vbTriviaList = (SyntaxTriviaList)vbToken.TrailingTrivia; Assert.Equal(2, vbTriviaList.Count); var vbTrivia = vbTriviaList.ElementAt(1); Assert.Equal(VB.SyntaxKind.CommentTrivia, VB.VisualBasicExtensions.Kind(vbTrivia)); var correctSpan = vbTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(14, correctSpan.End); var commonTrivia = (SyntaxTrivia)vbTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)vbTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)vbToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var vbTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, vbTrivia2.Span); var vbTriviaList2 = (SyntaxTriviaList)commonTriviaList; var vbTrivia3 = vbTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, vbTrivia3.Span); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void CSharpSyntax_VisualBasicKind() { var node = CSharp.SyntaxFactory.Identifier("a"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(node)); var token = CSharp.SyntaxFactory.Token(CSharp.SyntaxKind.IfKeyword); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(token)); var trivia = CSharp.SyntaxFactory.Comment("c"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(trivia)); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void VisualBasicSyntax_CSharpKind() { var node = VisualBasic.SyntaxFactory.Identifier("a"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(node)); var token = VisualBasic.SyntaxFactory.Token(VisualBasic.SyntaxKind.IfKeyword); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(token)); var trivia = VisualBasic.SyntaxFactory.CommentTrivia("c"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(trivia)); } [Fact] public void TestTrackNodes() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } [Fact] public void TestTrackNodesWithDuplicateIdAnnotations() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); var annotation = trackedExpr.GetAnnotatedNodes(SyntaxNodeExtensions.IdAnnotationKind).First() .GetAnnotations(SyntaxNodeExtensions.IdAnnotationKind).First(); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten).WithAdditionalAnnotations(annotation)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Xaml/Impl/Features/TypeRename/XamlTypeRenameResult.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.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.TypeRename { internal class XamlTypeRenameResult { public ImmutableArray<TextSpan> Ranges { get; set; } public string? WordPattern { get; set; } } }
// 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.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.TypeRename { internal class XamlTypeRenameResult { public ImmutableArray<TextSpan> Ranges { get; set; } public string? WordPattern { get; set; } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmCompilerId.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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; namespace Microsoft.VisualStudio.Debugger.Evaluation { public struct DkmCompilerId { public readonly Guid LanguageId; public readonly Guid VendorId; public DkmCompilerId(Guid vendorId, Guid languageId) { VendorId = vendorId; LanguageId = languageId; } } }
// 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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; namespace Microsoft.VisualStudio.Debugger.Evaluation { public struct DkmCompilerId { public readonly Guid LanguageId; public readonly Guid VendorId; public DkmCompilerId(Guid vendorId, Guid languageId) { VendorId = vendorId; LanguageId = languageId; } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Core/Impl/CodeModel/CodeModelProjectCache.CacheEntry.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.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal sealed partial class CodeModelProjectCache { private struct CacheEntry { // NOTE: The logic here is a little bit tricky. We can't just keep a WeakReference to // something like a ComHandle, since it's not something that our clients keep alive. // instead, we keep a weak reference to the inner managed object, which we know will // always be alive if the outer aggregate is alive. We can't just keep a WeakReference // to the RCW for the outer object either, since in cases where we have a DCOM or native // client, the RCW will be cleaned up, even though there is still a native reference // to the underlying native outer object. // // Instead we make use of an implementation detail of the way the CLR's COM aggregation // works. Namely, if all references to the aggregated object are released, the CLR // responds to QI's for IUnknown with a different object. So, we store the original // value, when we know that we have a client, and then we use that to compare to see // if we still have a client alive. // // NOTE: This is _NOT_ AddRef'd. We use it just to store the integer value of the // IUnknown for comparison purposes. private readonly WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> _fileCodeModelWeakComHandle; public CacheEntry(ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> handle) => _fileCodeModelWeakComHandle = new WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(handle); public EnvDTE80.FileCodeModel2 FileCodeModelRcw { get { return _fileCodeModelWeakComHandle.ComAggregateObject; } } internal bool TryGetFileCodeModelInstanceWithoutCaringWhetherRcwIsAlive(out FileCodeModel fileCodeModel) => _fileCodeModelWeakComHandle.TryGetManagedObjectWithoutCaringWhetherNativeObjectIsAlive(out fileCodeModel); public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? ComHandle { get { return _fileCodeModelWeakComHandle.ComHandle; } } } } }
// 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.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal sealed partial class CodeModelProjectCache { private struct CacheEntry { // NOTE: The logic here is a little bit tricky. We can't just keep a WeakReference to // something like a ComHandle, since it's not something that our clients keep alive. // instead, we keep a weak reference to the inner managed object, which we know will // always be alive if the outer aggregate is alive. We can't just keep a WeakReference // to the RCW for the outer object either, since in cases where we have a DCOM or native // client, the RCW will be cleaned up, even though there is still a native reference // to the underlying native outer object. // // Instead we make use of an implementation detail of the way the CLR's COM aggregation // works. Namely, if all references to the aggregated object are released, the CLR // responds to QI's for IUnknown with a different object. So, we store the original // value, when we know that we have a client, and then we use that to compare to see // if we still have a client alive. // // NOTE: This is _NOT_ AddRef'd. We use it just to store the integer value of the // IUnknown for comparison purposes. private readonly WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> _fileCodeModelWeakComHandle; public CacheEntry(ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> handle) => _fileCodeModelWeakComHandle = new WeakComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(handle); public EnvDTE80.FileCodeModel2 FileCodeModelRcw { get { return _fileCodeModelWeakComHandle.ComAggregateObject; } } internal bool TryGetFileCodeModelInstanceWithoutCaringWhetherRcwIsAlive(out FileCodeModel fileCodeModel) => _fileCodeModelWeakComHandle.TryGetManagedObjectWithoutCaringWhetherNativeObjectIsAlive(out fileCodeModel); public ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>? ComHandle { get { return _fileCodeModelWeakComHandle.ComHandle; } } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/Core/Portable/Completion/Providers/Scripting/AbstractDirectivePathCompletionProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Scripting; using Roslyn.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using System.Diagnostics; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractDirectivePathCompletionProvider : CompletionProvider { protected static bool IsDirectorySeparator(char ch) => ch == '/' || (ch == '\\' && !PathUtilities.IsUnixLikePlatform); protected abstract bool TryGetStringLiteralToken(SyntaxTree tree, int position, out SyntaxToken stringLiteral, CancellationToken cancellationToken); /// <summary> /// <code>r</code> for metadata reference directive, <code>load</code> for source file directive. /// </summary> protected abstract string DirectiveName { get; } public sealed override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (!TryGetStringLiteralToken(tree, position, out var stringLiteral, cancellationToken)) { return; } var literalValue = stringLiteral.ToString(); context.CompletionListSpan = GetTextChangeSpan( quotedPath: literalValue, quotedPathStart: stringLiteral.SpanStart, position: position); var pathThroughLastSlash = GetPathThroughLastSlash( quotedPath: literalValue, quotedPathStart: stringLiteral.SpanStart, position: position); await ProvideCompletionsAsync(context, pathThroughLastSlash).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } public sealed override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) { var lineStart = text.Lines.GetLineFromPosition(caretPosition).Start; // check if the line starts with {whitespace}#{whitespace}{DirectiveName}{whitespace}" var poundIndex = text.IndexOfNonWhiteSpace(lineStart, caretPosition - lineStart); if (poundIndex == -1 || text[poundIndex] != '#') { return false; } var directiveNameStartIndex = text.IndexOfNonWhiteSpace(poundIndex + 1, caretPosition - poundIndex - 1); if (directiveNameStartIndex == -1 || !text.ContentEquals(directiveNameStartIndex, DirectiveName)) { return false; } var directiveNameEndIndex = directiveNameStartIndex + DirectiveName.Length; var quoteIndex = text.IndexOfNonWhiteSpace(directiveNameEndIndex, caretPosition - directiveNameEndIndex); if (quoteIndex == -1 || text[quoteIndex] != '"') { return false; } return true; } private static string GetPathThroughLastSlash(string quotedPath, int quotedPathStart, int position) { Contract.ThrowIfTrue(quotedPath[0] != '"'); const int QuoteLength = 1; var positionInQuotedPath = position - quotedPathStart; var path = quotedPath[QuoteLength..positionInQuotedPath].Trim(); var afterLastSlashIndex = AfterLastSlashIndex(path, path.Length); // We want the portion up to, and including the last slash if there is one. That way if // the user pops up completion in the middle of a path (i.e. "C:\Win") then we'll // consider the path to be "C:\" and we will show appropriate completions. return afterLastSlashIndex >= 0 ? path.Substring(0, afterLastSlashIndex) : path; } private static TextSpan GetTextChangeSpan(string quotedPath, int quotedPathStart, int position) { // We want the text change to be from after the last slash to the end of the quoted // path. If there is no last slash, then we want it from right after the start quote // character. var positionInQuotedPath = position - quotedPathStart; // Where we want to start tracking is right after the slash (if we have one), or else // right after the string starts. var afterLastSlashIndex = AfterLastSlashIndex(quotedPath, positionInQuotedPath); var afterFirstQuote = 1; var startIndex = Math.Max(afterLastSlashIndex, afterFirstQuote); var endIndex = quotedPath.Length; // If the string ends with a quote, the we do not want to consume that. if (EndsWithQuote(quotedPath)) { endIndex--; } return TextSpan.FromBounds(startIndex + quotedPathStart, endIndex + quotedPathStart); } private static bool EndsWithQuote(string quotedPath) => quotedPath.Length >= 2 && quotedPath[quotedPath.Length - 1] == '"'; /// <summary> /// Returns the index right after the last slash that precedes 'position'. If there is no /// slash in the string, -1 is returned. /// </summary> private static int AfterLastSlashIndex(string text, int position) { // Position might be out of bounds of the string (if the string is unterminated. Make // sure it's within bounds. position = Math.Min(position, text.Length - 1); int index; if ((index = text.LastIndexOf('/', position)) >= 0 || !PathUtilities.IsUnixLikePlatform && (index = text.LastIndexOf('\\', position)) >= 0) { return index + 1; } return -1; } protected abstract Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash); protected static FileSystemCompletionHelper GetFileSystemCompletionHelper( Document document, Glyph itemGlyph, ImmutableArray<string> extensions, CompletionItemRules completionRules) { ImmutableArray<string> referenceSearchPaths; string? baseDirectory; if (document.Project.CompilationOptions?.MetadataReferenceResolver is RuntimeMetadataReferenceResolver resolver) { referenceSearchPaths = resolver.PathResolver.SearchPaths; baseDirectory = resolver.PathResolver.BaseDirectory; } else { referenceSearchPaths = ImmutableArray<string>.Empty; baseDirectory = null; } return new FileSystemCompletionHelper( Glyph.OpenFolder, itemGlyph, referenceSearchPaths, GetBaseDirectory(document, baseDirectory), extensions, completionRules); } private static string? GetBaseDirectory(Document document, string? baseDirectory) { var result = PathUtilities.GetDirectoryName(document.FilePath); if (!PathUtilities.IsAbsolute(result)) { result = baseDirectory; Debug.Assert(result == null || PathUtilities.IsAbsolute(result)); } 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. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Scripting; using Roslyn.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using System.Diagnostics; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractDirectivePathCompletionProvider : CompletionProvider { protected static bool IsDirectorySeparator(char ch) => ch == '/' || (ch == '\\' && !PathUtilities.IsUnixLikePlatform); protected abstract bool TryGetStringLiteralToken(SyntaxTree tree, int position, out SyntaxToken stringLiteral, CancellationToken cancellationToken); /// <summary> /// <code>r</code> for metadata reference directive, <code>load</code> for source file directive. /// </summary> protected abstract string DirectiveName { get; } public sealed override async Task ProvideCompletionsAsync(CompletionContext context) { try { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (!TryGetStringLiteralToken(tree, position, out var stringLiteral, cancellationToken)) { return; } var literalValue = stringLiteral.ToString(); context.CompletionListSpan = GetTextChangeSpan( quotedPath: literalValue, quotedPathStart: stringLiteral.SpanStart, position: position); var pathThroughLastSlash = GetPathThroughLastSlash( quotedPath: literalValue, quotedPathStart: stringLiteral.SpanStart, position: position); await ProvideCompletionsAsync(context, pathThroughLastSlash).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } public sealed override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) { var lineStart = text.Lines.GetLineFromPosition(caretPosition).Start; // check if the line starts with {whitespace}#{whitespace}{DirectiveName}{whitespace}" var poundIndex = text.IndexOfNonWhiteSpace(lineStart, caretPosition - lineStart); if (poundIndex == -1 || text[poundIndex] != '#') { return false; } var directiveNameStartIndex = text.IndexOfNonWhiteSpace(poundIndex + 1, caretPosition - poundIndex - 1); if (directiveNameStartIndex == -1 || !text.ContentEquals(directiveNameStartIndex, DirectiveName)) { return false; } var directiveNameEndIndex = directiveNameStartIndex + DirectiveName.Length; var quoteIndex = text.IndexOfNonWhiteSpace(directiveNameEndIndex, caretPosition - directiveNameEndIndex); if (quoteIndex == -1 || text[quoteIndex] != '"') { return false; } return true; } private static string GetPathThroughLastSlash(string quotedPath, int quotedPathStart, int position) { Contract.ThrowIfTrue(quotedPath[0] != '"'); const int QuoteLength = 1; var positionInQuotedPath = position - quotedPathStart; var path = quotedPath[QuoteLength..positionInQuotedPath].Trim(); var afterLastSlashIndex = AfterLastSlashIndex(path, path.Length); // We want the portion up to, and including the last slash if there is one. That way if // the user pops up completion in the middle of a path (i.e. "C:\Win") then we'll // consider the path to be "C:\" and we will show appropriate completions. return afterLastSlashIndex >= 0 ? path.Substring(0, afterLastSlashIndex) : path; } private static TextSpan GetTextChangeSpan(string quotedPath, int quotedPathStart, int position) { // We want the text change to be from after the last slash to the end of the quoted // path. If there is no last slash, then we want it from right after the start quote // character. var positionInQuotedPath = position - quotedPathStart; // Where we want to start tracking is right after the slash (if we have one), or else // right after the string starts. var afterLastSlashIndex = AfterLastSlashIndex(quotedPath, positionInQuotedPath); var afterFirstQuote = 1; var startIndex = Math.Max(afterLastSlashIndex, afterFirstQuote); var endIndex = quotedPath.Length; // If the string ends with a quote, the we do not want to consume that. if (EndsWithQuote(quotedPath)) { endIndex--; } return TextSpan.FromBounds(startIndex + quotedPathStart, endIndex + quotedPathStart); } private static bool EndsWithQuote(string quotedPath) => quotedPath.Length >= 2 && quotedPath[quotedPath.Length - 1] == '"'; /// <summary> /// Returns the index right after the last slash that precedes 'position'. If there is no /// slash in the string, -1 is returned. /// </summary> private static int AfterLastSlashIndex(string text, int position) { // Position might be out of bounds of the string (if the string is unterminated. Make // sure it's within bounds. position = Math.Min(position, text.Length - 1); int index; if ((index = text.LastIndexOf('/', position)) >= 0 || !PathUtilities.IsUnixLikePlatform && (index = text.LastIndexOf('\\', position)) >= 0) { return index + 1; } return -1; } protected abstract Task ProvideCompletionsAsync(CompletionContext context, string pathThroughLastSlash); protected static FileSystemCompletionHelper GetFileSystemCompletionHelper( Document document, Glyph itemGlyph, ImmutableArray<string> extensions, CompletionItemRules completionRules) { ImmutableArray<string> referenceSearchPaths; string? baseDirectory; if (document.Project.CompilationOptions?.MetadataReferenceResolver is RuntimeMetadataReferenceResolver resolver) { referenceSearchPaths = resolver.PathResolver.SearchPaths; baseDirectory = resolver.PathResolver.BaseDirectory; } else { referenceSearchPaths = ImmutableArray<string>.Empty; baseDirectory = null; } return new FileSystemCompletionHelper( Glyph.OpenFolder, itemGlyph, referenceSearchPaths, GetBaseDirectory(document, baseDirectory), extensions, completionRules); } private static string? GetBaseDirectory(Document document, string? baseDirectory) { var result = PathUtilities.GetDirectoryName(document.FilePath); if (!PathUtilities.IsAbsolute(result)) { result = baseDirectory; Debug.Assert(result == null || PathUtilities.IsAbsolute(result)); } return result; } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/Core/Portable/Intents/IIntentProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Features.Intents { internal interface IIntentProvider { Task<ImmutableArray<IntentProcessorResult>> ComputeIntentAsync( Document priorDocument, TextSpan priorSelection, Document currentDocument, string? serializedIntentData, 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Features.Intents { internal interface IIntentProvider { Task<ImmutableArray<IntentProcessorResult>> ComputeIntentAsync( Document priorDocument, TextSpan priorSelection, Document currentDocument, string? serializedIntentData, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/CSharp/Impl/CodeModel/Interop/ICSAutoImplementedPropertyExtender.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.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("b093257b-fe0c-4302-ad0f-38e276e57619")] internal interface ICSAutoImplementedPropertyExtender { bool IsAutoImplemented { 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 using System; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("b093257b-fe0c-4302-ad0f-38e276e57619")] internal interface ICSAutoImplementedPropertyExtender { bool IsAutoImplemented { get; } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/CSharp/Portable/Symbols/Wrapped/WrappedNamedTypeSymbol.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 System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a named type that is based on another named type. /// When inheriting from this class, one shouldn't assume that /// the default behavior it has is appropriate for every case. /// That behavior should be carefully reviewed and derived type /// should override behavior as appropriate. /// </summary> internal abstract class WrappedNamedTypeSymbol : NamedTypeSymbol { /// <summary> /// The underlying NamedTypeSymbol. /// </summary> protected readonly NamedTypeSymbol _underlyingType; public WrappedNamedTypeSymbol(NamedTypeSymbol underlyingType, TupleExtraData tupleData) : base(tupleData) { Debug.Assert((object)underlyingType != null); _underlyingType = underlyingType; } public NamedTypeSymbol UnderlyingNamedType { get { return _underlyingType; } } public override bool IsImplicitlyDeclared { get { return _underlyingType.IsImplicitlyDeclared; } } public override int Arity { get { return _underlyingType.Arity; } } public override bool MightContainExtensionMethods { get { return _underlyingType.MightContainExtensionMethods; } } public override string Name { get { return _underlyingType.Name; } } public override string MetadataName { get { return _underlyingType.MetadataName; } } internal override bool HasSpecialName { get { return _underlyingType.HasSpecialName; } } internal override bool MangleName { get { return _underlyingType.MangleName; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return _underlyingType.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } public override Accessibility DeclaredAccessibility { get { return _underlyingType.DeclaredAccessibility; } } public override TypeKind TypeKind { get { return _underlyingType.TypeKind; } } internal override bool IsInterface { get { return _underlyingType.IsInterface; } } public override ImmutableArray<Location> Locations { get { if (IsTupleType) { return TupleData.Locations; } return _underlyingType.Locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { if (IsTupleType) { return GetDeclaringSyntaxReferenceHelper<CSharpSyntaxNode>(TupleData.Locations); } return _underlyingType.DeclaringSyntaxReferences; } } public override bool IsStatic { get { return _underlyingType.IsStatic; } } public override bool IsAbstract { get { return _underlyingType.IsAbstract; } } internal override bool IsMetadataAbstract { get { return _underlyingType.IsMetadataAbstract; } } public override bool IsSealed { get { return _underlyingType.IsSealed; } } internal override bool IsMetadataSealed { get { return _underlyingType.IsMetadataSealed; } } internal override bool HasCodeAnalysisEmbeddedAttribute => _underlyingType.HasCodeAnalysisEmbeddedAttribute; internal override bool IsInterpolatedStringHandlerType => _underlyingType.IsInterpolatedStringHandlerType; internal override ObsoleteAttributeData ObsoleteAttributeData { get { return _underlyingType.ObsoleteAttributeData; } } internal override bool ShouldAddWinRTMembers { get { return _underlyingType.ShouldAddWinRTMembers; } } internal override bool IsWindowsRuntimeImport { get { return _underlyingType.IsWindowsRuntimeImport; } } internal override TypeLayout Layout { get { return _underlyingType.Layout; } } internal override CharSet MarshallingCharSet { get { return _underlyingType.MarshallingCharSet; } } public override bool IsSerializable { get { return _underlyingType.IsSerializable; } } public override bool IsRefLikeType { get { return _underlyingType.IsRefLikeType; } } public override bool IsReadOnly { get { return _underlyingType.IsReadOnly; } } internal override bool HasDeclarativeSecurity { get { return _underlyingType.HasDeclarativeSecurity; } } internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { return _underlyingType.GetSecurityInformation(); } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return _underlyingType.GetAppliedConditionalSymbols(); } internal override AttributeUsageInfo GetAttributeUsageInfo() { return _underlyingType.GetAttributeUsageInfo(); } internal override bool GetGuidString(out string guidString) { return _underlyingType.GetGuidString(out guidString); } } }
// 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 System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a named type that is based on another named type. /// When inheriting from this class, one shouldn't assume that /// the default behavior it has is appropriate for every case. /// That behavior should be carefully reviewed and derived type /// should override behavior as appropriate. /// </summary> internal abstract class WrappedNamedTypeSymbol : NamedTypeSymbol { /// <summary> /// The underlying NamedTypeSymbol. /// </summary> protected readonly NamedTypeSymbol _underlyingType; public WrappedNamedTypeSymbol(NamedTypeSymbol underlyingType, TupleExtraData tupleData) : base(tupleData) { Debug.Assert((object)underlyingType != null); _underlyingType = underlyingType; } public NamedTypeSymbol UnderlyingNamedType { get { return _underlyingType; } } public override bool IsImplicitlyDeclared { get { return _underlyingType.IsImplicitlyDeclared; } } public override int Arity { get { return _underlyingType.Arity; } } public override bool MightContainExtensionMethods { get { return _underlyingType.MightContainExtensionMethods; } } public override string Name { get { return _underlyingType.Name; } } public override string MetadataName { get { return _underlyingType.MetadataName; } } internal override bool HasSpecialName { get { return _underlyingType.HasSpecialName; } } internal override bool MangleName { get { return _underlyingType.MangleName; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return _underlyingType.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } public override Accessibility DeclaredAccessibility { get { return _underlyingType.DeclaredAccessibility; } } public override TypeKind TypeKind { get { return _underlyingType.TypeKind; } } internal override bool IsInterface { get { return _underlyingType.IsInterface; } } public override ImmutableArray<Location> Locations { get { if (IsTupleType) { return TupleData.Locations; } return _underlyingType.Locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { if (IsTupleType) { return GetDeclaringSyntaxReferenceHelper<CSharpSyntaxNode>(TupleData.Locations); } return _underlyingType.DeclaringSyntaxReferences; } } public override bool IsStatic { get { return _underlyingType.IsStatic; } } public override bool IsAbstract { get { return _underlyingType.IsAbstract; } } internal override bool IsMetadataAbstract { get { return _underlyingType.IsMetadataAbstract; } } public override bool IsSealed { get { return _underlyingType.IsSealed; } } internal override bool IsMetadataSealed { get { return _underlyingType.IsMetadataSealed; } } internal override bool HasCodeAnalysisEmbeddedAttribute => _underlyingType.HasCodeAnalysisEmbeddedAttribute; internal override bool IsInterpolatedStringHandlerType => _underlyingType.IsInterpolatedStringHandlerType; internal override ObsoleteAttributeData ObsoleteAttributeData { get { return _underlyingType.ObsoleteAttributeData; } } internal override bool ShouldAddWinRTMembers { get { return _underlyingType.ShouldAddWinRTMembers; } } internal override bool IsWindowsRuntimeImport { get { return _underlyingType.IsWindowsRuntimeImport; } } internal override TypeLayout Layout { get { return _underlyingType.Layout; } } internal override CharSet MarshallingCharSet { get { return _underlyingType.MarshallingCharSet; } } public override bool IsSerializable { get { return _underlyingType.IsSerializable; } } public override bool IsRefLikeType { get { return _underlyingType.IsRefLikeType; } } public override bool IsReadOnly { get { return _underlyingType.IsReadOnly; } } internal override bool HasDeclarativeSecurity { get { return _underlyingType.HasDeclarativeSecurity; } } internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { return _underlyingType.GetSecurityInformation(); } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return _underlyingType.GetAppliedConditionalSymbols(); } internal override AttributeUsageInfo GetAttributeUsageInfo() { return _underlyingType.GetAttributeUsageInfo(); } internal override bool GetGuidString(out string guidString) { return _underlyingType.GetGuidString(out guidString); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/ObjectList.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.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServices.Implementation.F1Help; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal class ObjectList : AbstractObjectList<AbstractObjectBrowserLibraryManager> { private readonly ObjectListKind _kind; private readonly ObjectList _parentList; private readonly ObjectListItem _parentListItem; private readonly uint _flags; private readonly AbstractObjectBrowserLibraryManager _manager; private readonly ImmutableArray<ObjectListItem> _items; public ObjectList( ObjectListKind kind, uint flags, AbstractObjectBrowserLibraryManager manager, ImmutableArray<ObjectListItem> items) : this(kind, flags, null, null, manager, items) { } public ObjectList( ObjectListKind kind, uint flags, ObjectList parentList, ObjectListItem parentListItem, AbstractObjectBrowserLibraryManager manager, ImmutableArray<ObjectListItem> items) : base(manager) { _kind = kind; _flags = flags; _parentList = parentList; _parentListItem = parentListItem; _manager = manager; _items = items; foreach (var item in _items) { item.SetParentList(this); } } private bool IsClassView() => Helpers.IsClassView(_flags); private ObjectListItem GetListItem(uint index) { var listItem = _items[(int)index]; this.LibraryManager.SetActiveListItem(listItem); return listItem; } private string GetDisplayText(uint index, VSTREETEXTOPTIONS textOptions) { var listItem = GetListItem(index); switch (textOptions) { case VSTREETEXTOPTIONS.TTO_SORTTEXT: case VSTREETEXTOPTIONS.TTO_DISPLAYTEXT: switch (_kind) { case ObjectListKind.BaseTypes: case ObjectListKind.Hierarchy: case ObjectListKind.Members: case ObjectListKind.Namespaces: case ObjectListKind.Projects: case ObjectListKind.References: case ObjectListKind.Types: return listItem.DisplayText; } break; } return listItem.DisplayText; } protected override bool CanGoToSource(uint index, VSOBJGOTOSRCTYPE srcType) { if (srcType == VSOBJGOTOSRCTYPE.GS_DEFINITION) { if (GetListItem(index) is SymbolListItem symbolItem) { return symbolItem.SupportsGoToDefinition; } } return false; } protected override bool TryGetCapabilities(out uint capabilities) { capabilities = (uint)_LIB_LISTCAPABILITIES2.LLC_ALLOWELEMENTSEARCH; return true; } private bool TryGetListType(out uint categoryField) { switch (_kind) { case ObjectListKind.BaseTypes: categoryField = (uint)_LIB_LISTTYPE.LLT_CLASSES | (uint)_LIB_LISTTYPE.LLT_MEMBERS; return true; case ObjectListKind.Hierarchy: var parentKind = this.ParentKind; categoryField = parentKind is ObjectListKind.Types or ObjectListKind.BaseTypes ? (uint)_LIB_LISTTYPE.LLT_CLASSES : (uint)_LIB_LISTTYPE.LLT_PACKAGE; return true; case ObjectListKind.Members: categoryField = 0; return true; case ObjectListKind.Namespaces: categoryField = (uint)_LIB_LISTTYPE.LLT_CLASSES; return true; case ObjectListKind.Projects: categoryField = (uint)_LIB_LISTTYPE.LLT_NAMESPACES | (uint)_LIB_LISTTYPE.LLT_CLASSES; if (IsClassView() && this.ParentKind == ObjectListKind.None) { categoryField |= (uint)_LIB_LISTTYPE.LLT_HIERARCHY; } return true; case ObjectListKind.References: categoryField = (uint)_LIB_LISTTYPE.LLT_NAMESPACES | (uint)_LIB_LISTTYPE.LLT_CLASSES; return true; case ObjectListKind.Types: categoryField = (uint)_LIB_LISTTYPE.LLT_MEMBERS; if ((_flags & (Helpers.LLF_SEARCH_EXPAND_MEMBERS | Helpers.LLF_SEARCH_WITH_EXPANSION)) == 0) { categoryField |= (uint)_LIB_LISTTYPE.LLT_HIERARCHY; } return true; } categoryField = 0; return false; } private bool TryGetClassAccess(uint index, out uint categoryField) { var typeListItem = (TypeListItem)GetListItem(index); switch (typeListItem.Accessibility) { case Accessibility.Private: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PRIVATE; return true; case Accessibility.Protected: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PROTECTED; return true; case Accessibility.Internal: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PACKAGE; return true; default: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PUBLIC; return true; } } private bool TryGetClassType(uint index, out uint categoryField) { var typeListItem = (TypeListItem)GetListItem(index); switch (typeListItem.Kind) { case TypeKind.Interface: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_INTERFACE; return true; case TypeKind.Struct: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_STRUCT; return true; case TypeKind.Enum: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_ENUM; return true; case TypeKind.Delegate: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_DELEGATE; return true; case TypeKind.Class: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_CLASS; return true; case TypeKind.Module: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_MODULE; return true; default: Debug.Fail("Unexpected type kind: " + typeListItem.Kind.ToString()); categoryField = 0; return false; } } private bool TryGetMemberInheritance(uint index, out uint categoryField) { var memberListItem = (MemberListItem)GetListItem(index); if (memberListItem.IsInherited) { categoryField = (uint)_LIBCAT_MEMBERINHERITANCE.LCMI_INHERITED; } else { categoryField = (uint)_LIBCAT_MEMBERINHERITANCE.LCMI_IMMEDIATE; } return true; } private bool TryGetMemberAccess(uint index, out uint categoryField) { var memberListItem = (MemberListItem)GetListItem(index); switch (memberListItem.Accessibility) { case Accessibility.Private: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PRIVATE; return true; case Accessibility.Protected: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PROTECTED; return true; case Accessibility.Internal: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PACKAGE; return true; default: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PUBLIC; return true; } } private bool TryGetMemberType(uint index, out uint categoryField) { var memberListItem = (MemberListItem)GetListItem(index); switch (memberListItem.Kind) { case MemberKind.Constant: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_CONSTANT; return true; case MemberKind.EnumMember: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_ENUMITEM; return true; case MemberKind.Event: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_EVENT; return true; case MemberKind.Field: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_FIELD; return true; case MemberKind.Method: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_METHOD; return true; case MemberKind.Operator: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_OPERATOR; return true; case MemberKind.Property: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_PROPERTY; return true; default: Debug.Fail("Unexpected member kind: " + memberListItem.Kind.ToString()); categoryField = 0; return false; } } private bool TryGetPhysicalContainerType(uint index, out uint categoryField) { var listItem = GetListItem(index); switch (listItem.ParentListKind) { case ObjectListKind.Projects: categoryField = (uint)_LIBCAT_PHYSICALCONTAINERTYPE.LCPT_PROJECT; return true; case ObjectListKind.References: categoryField = (uint)_LIBCAT_PHYSICALCONTAINERTYPE.LCPT_PROJECTREFERENCE; return true; } categoryField = 0; return false; } private bool TryGetVisibility(uint index, out uint categoryField) { var item = GetListItem(index); categoryField = item.IsHidden ? (uint)_LIBCAT_VISIBILITY.LCV_HIDDEN : (uint)_LIBCAT_VISIBILITY.LCV_VISIBLE; return true; } protected override bool TryGetCategoryField(uint index, int category, out uint categoryField) { switch (category) { case (int)LIB_CATEGORY.LC_LISTTYPE: return TryGetListType(out categoryField); case (int)_LIB_CATEGORY2.LC_MEMBERINHERITANCE: return TryGetMemberInheritance(index, out categoryField); case (int)LIB_CATEGORY.LC_MEMBERACCESS: return TryGetMemberAccess(index, out categoryField); case (int)LIB_CATEGORY.LC_MEMBERTYPE: return TryGetMemberType(index, out categoryField); case (int)LIB_CATEGORY.LC_CLASSACCESS: return TryGetClassAccess(index, out categoryField); case (int)LIB_CATEGORY.LC_CLASSTYPE: return TryGetClassType(index, out categoryField); case (int)_LIB_CATEGORY2.LC_HIERARCHYTYPE: if (_kind == ObjectListKind.Hierarchy) { categoryField = this.ParentKind == ObjectListKind.Projects ? (uint)_LIBCAT_HIERARCHYTYPE.LCHT_PROJECTREFERENCES : (uint)_LIBCAT_HIERARCHYTYPE.LCHT_BASESANDINTERFACES; } else { categoryField = (uint)_LIBCAT_HIERARCHYTYPE.LCHT_UNKNOWN; } return true; case (int)LIB_CATEGORY.LC_NODETYPE: categoryField = 0; return false; case (int)_LIB_CATEGORY2.LC_PHYSICALCONTAINERTYPE: return TryGetPhysicalContainerType(index, out categoryField); case (int)LIB_CATEGORY.LC_VISIBILITY: return TryGetVisibility(index, out categoryField); } throw new NotImplementedException(); } protected override void GetDisplayData(uint index, ref VSTREEDISPLAYDATA data) { var item = GetListItem(index); data.Image = item.GlyphIndex; data.SelectedImage = item.GlyphIndex; if (item.IsHidden) { data.State |= (uint)_VSTREEDISPLAYSTATE.TDS_GRAYTEXT; } } protected override bool GetExpandable(uint index, uint listTypeExcluded) { switch (_kind) { case ObjectListKind.Hierarchy: case ObjectListKind.Namespaces: case ObjectListKind.Projects: case ObjectListKind.References: return true; case ObjectListKind.BaseTypes: case ObjectListKind.Types: return IsExpandableType(index); } return false; } private bool IsExpandableType(uint index) { if (GetListItem(index) is not TypeListItem typeListItem) { return false; } var compilation = typeListItem.GetCompilation(this.LibraryManager.Workspace); if (compilation == null) { return false; } var typeSymbol = typeListItem.ResolveTypedSymbol(compilation); // We never show base types for System.Object if (typeSymbol.SpecialType == SpecialType.System_Object) { return false; } if (typeSymbol.TypeKind == TypeKind.Module) { return false; } if (typeSymbol.TypeKind == TypeKind.Interface && typeSymbol.Interfaces.IsEmpty) { return false; } if (typeSymbol.BaseType == null) { return false; } return true; } protected override uint GetItemCount() => (uint)_items.Length; protected override IVsSimpleObjectList2 GetList(uint index, uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch) { var listItem = GetListItem(index); // We need to do a little massaging of the list type and parent item in a couple of cases. switch (_kind) { case ObjectListKind.Hierarchy: // LLT_USESCLASSES is for displaying base classes and interfaces // LLF_PROJREF is for displaying project references listType = listType == (uint)_LIB_LISTTYPE.LLT_CLASSES ? (uint)_LIB_LISTTYPE.LLT_USESCLASSES : Helpers.LLT_PROJREF; // Use the parent of this list as the parent of the new list. listItem = listItem.ParentList._parentListItem; break; case ObjectListKind.BaseTypes: if (listType == (uint)_LIB_LISTTYPE.LLT_CLASSES) { listType = (uint)_LIB_LISTTYPE.LLT_USESCLASSES; } break; } var listKind = Helpers.ListTypeToObjectListKind(listType); if (Helpers.IsFindSymbol(flags)) { var project = this.LibraryManager.GetProject(listItem.ProjectId); if (project == null) { return null; } var lookInReferences = (flags & ((uint)_VSOBSEARCHOPTIONS.VSOBSO_LOOKINREFS | (uint)_VSOBSEARCHOPTIONS2.VSOBSO_LISTREFERENCES)) != 0; var projectAndAssemblySet = this.LibraryManager.GetAssemblySet(project, lookInReferences, CancellationToken.None); return this.LibraryManager.GetSearchList(listKind, flags, pobSrch, projectAndAssemblySet); } var compilation = listItem.GetCompilation(this.LibraryManager.Workspace); if (compilation == null) { return null; } switch (listKind) { case ObjectListKind.Types: return new ObjectList(ObjectListKind.Types, flags, this, listItem, _manager, this.LibraryManager.GetTypeListItems(listItem, compilation)); case ObjectListKind.Hierarchy: return new ObjectList(ObjectListKind.Hierarchy, flags, this, listItem, _manager, this.LibraryManager.GetFolderListItems(listItem, compilation)); case ObjectListKind.Namespaces: return new ObjectList(ObjectListKind.Namespaces, flags, this, listItem, _manager, this.LibraryManager.GetNamespaceListItems(listItem, compilation)); case ObjectListKind.Members: return new ObjectList(ObjectListKind.Members, flags, this, listItem, _manager, this.LibraryManager.GetMemberListItems(listItem, compilation)); case ObjectListKind.References: return new ObjectList(ObjectListKind.References, flags, this, listItem, _manager, this.LibraryManager.GetReferenceListItems(listItem, compilation)); case ObjectListKind.BaseTypes: return new ObjectList(ObjectListKind.BaseTypes, flags, this, listItem, _manager, this.LibraryManager.GetBaseTypeListItems(listItem, compilation)); } throw new NotImplementedException(); } protected override object GetBrowseObject(uint index) { if (GetListItem(index) is SymbolListItem symbolListItem) { return this.LibraryManager.Workspace.GetBrowseObject(symbolListItem); } return base.GetBrowseObject(index); } protected override bool SupportsNavInfo { get { return true; } } protected override IVsNavInfo GetNavInfo(uint index) { var listItem = GetListItem(index); if (listItem == null) { return null; } if (listItem is ProjectListItem projectListItem) { var project = this.LibraryManager.GetProject(projectListItem.ProjectId); if (project != null) { return this.LibraryManager.LibraryService.NavInfoFactory.CreateForProject(project); } } if (listItem is ReferenceListItem referenceListItem) { return this.LibraryManager.LibraryService.NavInfoFactory.CreateForReference(referenceListItem.MetadataReference); } if (listItem is SymbolListItem symbolListItem) { return this.LibraryManager.GetNavInfo(symbolListItem, useExpandedHierarchy: IsClassView()); } return null; } protected override IVsNavInfoNode GetNavInfoNode(uint index) { var listItem = GetListItem(index); var name = listItem.DisplayText; var type = Helpers.ObjectListKindToListType(_kind); if (type == (uint)_LIB_LISTTYPE.LLT_USESCLASSES) { type = (uint)_LIB_LISTTYPE.LLT_CLASSES; } else if (type == Helpers.LLT_PROJREF) { type = (uint)_LIB_LISTTYPE.LLT_PACKAGE; } return new NavInfoNode(name, type); } protected override bool TryLocateNavInfoNode(IVsNavInfoNode pNavInfoNode, out uint index) { var itemCount = GetItemCount(); index = 0xffffffffu; if (ErrorHandler.Failed(pNavInfoNode.get_Name(out var matchName))) { return false; } if (ErrorHandler.Failed(pNavInfoNode.get_Type(out _))) { return false; } var longestMatchedName = string.Empty; for (uint i = 0; i < itemCount; i++) { var name = GetText(i, VSTREETEXTOPTIONS.TTO_DISPLAYTEXT); if (_kind is ObjectListKind.Types or ObjectListKind.Namespaces or ObjectListKind.Members) { if (string.Equals(matchName, name, StringComparison.Ordinal)) { index = i; break; } } else { if (string.Equals(matchName, name, StringComparison.Ordinal)) { index = i; break; } else if (_kind == ObjectListKind.Projects) { if (matchName.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0) { if (longestMatchedName.Length < name.Length) { longestMatchedName = name; index = i; } } } } } return index != 0xffffffffu; } protected override bool SupportsDescription { get { return true; } } protected override bool TryFillDescription(uint index, _VSOBJDESCOPTIONS options, IVsObjectBrowserDescription3 description) { var listItem = GetListItem(index); return this.LibraryManager.TryFillDescription(listItem, description, options); } protected override bool TryGetProperty(uint index, _VSOBJLISTELEMPROPID propertyId, out object pvar) { pvar = null; var listItem = GetListItem(index); if (listItem == null) { return false; } switch (propertyId) { case _VSOBJLISTELEMPROPID.VSOBJLISTELEMPROPID_FULLNAME: pvar = listItem.FullNameText; return true; case _VSOBJLISTELEMPROPID.VSOBJLISTELEMPROPID_HELPKEYWORD: if (listItem is SymbolListItem symbolListItem) { var project = this.LibraryManager.Workspace.CurrentSolution.GetProject(symbolListItem.ProjectId); if (project != null) { var compilation = project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult_ObjectBrowser(CancellationToken.None); var symbol = symbolListItem.ResolveSymbol(compilation); if (symbol != null) { var helpContextService = project.LanguageServices.GetService<IHelpContextService>(); pvar = helpContextService.FormatSymbol(symbol); return true; } } } return false; } return false; } protected override bool TryCountSourceItems(uint index, out IVsHierarchy hierarchy, out uint itemid, out uint items) { hierarchy = null; itemid = 0; items = 0; var listItem = GetListItem(index); if (listItem == null) { return false; } hierarchy = this.LibraryManager.Workspace.GetHierarchy(listItem.ProjectId); if (listItem is ProjectListItem) { itemid = (uint)VSConstants.VSITEMID.Root; items = 1; return true; } else if (listItem is SymbolListItem) { // TODO: Get itemid items = 1; return true; } return false; } protected override string GetText(uint index, VSTREETEXTOPTIONS tto) => GetDisplayText(index, tto); protected override string GetTipText(uint index, VSTREETOOLTIPTYPE eTipType) => null; protected override async Task GoToSourceAsync(uint index, VSOBJGOTOSRCTYPE srcType) { try { using var token = _manager.AsynchronousOperationListener.BeginAsyncOperation(nameof(GoToSourceAsync)); using var context = _manager.OperationExecutor.BeginExecute(ServicesVSResources.IntelliSense, EditorFeaturesResources.Navigating, allowCancellation: true, showProgress: false); var cancellationToken = context.UserCancellationToken; if (srcType == VSOBJGOTOSRCTYPE.GS_DEFINITION && GetListItem(index) is SymbolListItem symbolItem && symbolItem.SupportsGoToDefinition) { var project = this.LibraryManager.Workspace.CurrentSolution.GetProject(symbolItem.ProjectId); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var symbol = symbolItem.ResolveSymbol(compilation); await this.LibraryManager.Workspace.TryGoToDefinitionAsync(symbol, project, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) { } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { } } protected override uint GetUpdateCounter() { switch (_kind) { case ObjectListKind.Projects: case ObjectListKind.References: return _manager.PackageVersion; case ObjectListKind.BaseTypes: case ObjectListKind.Namespaces: case ObjectListKind.Types: return _manager.ClassVersion; case ObjectListKind.Members: return _manager.MembersVersion; case ObjectListKind.Hierarchy: return _manager.ClassVersion | _manager.MembersVersion; default: Debug.Fail("Unsupported object list kind: " + _kind.ToString()); throw new InvalidOperationException(); } } protected override bool TryGetContextMenu(uint index, out Guid menuGuid, out int menuId) { if (GetListItem(index) == null) { menuGuid = Guid.Empty; menuId = 0; return false; } menuGuid = VsMenus.guidSHLMainMenu; // from vsshlids.h const int IDM_VS_CTXT_CV_PROJECT = 0x0432; const int IDM_VS_CTXT_CV_ITEM = 0x0433; const int IDM_VS_CTXT_CV_GROUPINGFOLDER = 0x0435; const int IDM_VS_CTXT_CV_MEMBER = 0x0438; switch (_kind) { case ObjectListKind.Projects: menuId = IDM_VS_CTXT_CV_PROJECT; break; case ObjectListKind.Members: menuId = IDM_VS_CTXT_CV_MEMBER; break; case ObjectListKind.Hierarchy: menuId = IDM_VS_CTXT_CV_GROUPINGFOLDER; break; default: menuId = IDM_VS_CTXT_CV_ITEM; break; } return true; } protected override bool SupportsBrowseContainers { get { return true; } } protected override bool TryFindBrowseContainer(VSCOMPONENTSELECTORDATA data, out uint index) { index = 0; var count = GetItemCount(); for (uint i = 0; i < count; i++) { var listItem = GetListItem(i); if (data.type == VSCOMPONENTTYPE.VSCOMPONENTTYPE_ComPlus) { if (listItem is not ReferenceListItem referenceListItem) { continue; } if (referenceListItem.MetadataReference is not PortableExecutableReference metadataReference) { continue; } if (string.Equals(data.bstrFile, metadataReference.FilePath, StringComparison.OrdinalIgnoreCase)) { index = i; return true; } } else { Debug.Assert(data.type == VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project); var hierarchy = this.LibraryManager.Workspace.GetHierarchy(listItem.ProjectId); if (hierarchy == null) { continue; } if (this.LibraryManager.ServiceProvider.GetService(typeof(SVsSolution)) is not IVsSolution vsSolution) { return false; } if (ErrorHandler.Failed(vsSolution.GetProjrefOfProject(hierarchy, out var projectRef))) { return false; } if (data.bstrProjRef == projectRef) { index = i; return true; } } } return false; } protected override bool TryGetBrowseContainerData(uint index, ref VSCOMPONENTSELECTORDATA data) { var listItem = GetListItem(index); if (listItem is ProjectListItem projectListItem) { var hierarchy = this.LibraryManager.Workspace.GetHierarchy(projectListItem.ProjectId); if (hierarchy == null) { return false; } if (this.LibraryManager.ServiceProvider.GetService(typeof(SVsSolution)) is not IVsSolution vsSolution) { return false; } if (ErrorHandler.Failed(vsSolution.GetProjrefOfProject(hierarchy, out var projectRef))) { return false; } var project = this.LibraryManager.Workspace.CurrentSolution.GetProject(projectListItem.ProjectId); if (project == null) { return false; } data.bstrFile = project.FilePath; data.bstrProjRef = projectRef; data.bstrTitle = projectListItem.DisplayText; data.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project; } else { if (listItem is not ReferenceListItem referenceListItem) { return false; } if (referenceListItem.MetadataReference is not PortableExecutableReference portableExecutableReference) { return false; } var assemblyIdentity = AssemblyIdentityUtils.TryGetAssemblyIdentity(portableExecutableReference.FilePath); if (assemblyIdentity == null) { return false; } data.bstrFile = portableExecutableReference.FilePath; data.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_ComPlus; data.wFileMajorVersion = (ushort)assemblyIdentity.Version.Major; data.wFileMinorVersion = (ushort)assemblyIdentity.Version.Minor; data.wFileBuildNumber = (ushort)assemblyIdentity.Version.Build; data.wFileRevisionNumber = (ushort)assemblyIdentity.Version.Revision; } return true; } public ObjectListKind Kind { get { return _kind; } } public ObjectListKind ParentKind { get { return _parentList != null ? _parentList.Kind : ObjectListKind.None; } } public ObjectListItem ParentListItem { get { return _parentListItem; } } } }
// 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.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServices.Implementation.F1Help; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal class ObjectList : AbstractObjectList<AbstractObjectBrowserLibraryManager> { private readonly ObjectListKind _kind; private readonly ObjectList _parentList; private readonly ObjectListItem _parentListItem; private readonly uint _flags; private readonly AbstractObjectBrowserLibraryManager _manager; private readonly ImmutableArray<ObjectListItem> _items; public ObjectList( ObjectListKind kind, uint flags, AbstractObjectBrowserLibraryManager manager, ImmutableArray<ObjectListItem> items) : this(kind, flags, null, null, manager, items) { } public ObjectList( ObjectListKind kind, uint flags, ObjectList parentList, ObjectListItem parentListItem, AbstractObjectBrowserLibraryManager manager, ImmutableArray<ObjectListItem> items) : base(manager) { _kind = kind; _flags = flags; _parentList = parentList; _parentListItem = parentListItem; _manager = manager; _items = items; foreach (var item in _items) { item.SetParentList(this); } } private bool IsClassView() => Helpers.IsClassView(_flags); private ObjectListItem GetListItem(uint index) { var listItem = _items[(int)index]; this.LibraryManager.SetActiveListItem(listItem); return listItem; } private string GetDisplayText(uint index, VSTREETEXTOPTIONS textOptions) { var listItem = GetListItem(index); switch (textOptions) { case VSTREETEXTOPTIONS.TTO_SORTTEXT: case VSTREETEXTOPTIONS.TTO_DISPLAYTEXT: switch (_kind) { case ObjectListKind.BaseTypes: case ObjectListKind.Hierarchy: case ObjectListKind.Members: case ObjectListKind.Namespaces: case ObjectListKind.Projects: case ObjectListKind.References: case ObjectListKind.Types: return listItem.DisplayText; } break; } return listItem.DisplayText; } protected override bool CanGoToSource(uint index, VSOBJGOTOSRCTYPE srcType) { if (srcType == VSOBJGOTOSRCTYPE.GS_DEFINITION) { if (GetListItem(index) is SymbolListItem symbolItem) { return symbolItem.SupportsGoToDefinition; } } return false; } protected override bool TryGetCapabilities(out uint capabilities) { capabilities = (uint)_LIB_LISTCAPABILITIES2.LLC_ALLOWELEMENTSEARCH; return true; } private bool TryGetListType(out uint categoryField) { switch (_kind) { case ObjectListKind.BaseTypes: categoryField = (uint)_LIB_LISTTYPE.LLT_CLASSES | (uint)_LIB_LISTTYPE.LLT_MEMBERS; return true; case ObjectListKind.Hierarchy: var parentKind = this.ParentKind; categoryField = parentKind is ObjectListKind.Types or ObjectListKind.BaseTypes ? (uint)_LIB_LISTTYPE.LLT_CLASSES : (uint)_LIB_LISTTYPE.LLT_PACKAGE; return true; case ObjectListKind.Members: categoryField = 0; return true; case ObjectListKind.Namespaces: categoryField = (uint)_LIB_LISTTYPE.LLT_CLASSES; return true; case ObjectListKind.Projects: categoryField = (uint)_LIB_LISTTYPE.LLT_NAMESPACES | (uint)_LIB_LISTTYPE.LLT_CLASSES; if (IsClassView() && this.ParentKind == ObjectListKind.None) { categoryField |= (uint)_LIB_LISTTYPE.LLT_HIERARCHY; } return true; case ObjectListKind.References: categoryField = (uint)_LIB_LISTTYPE.LLT_NAMESPACES | (uint)_LIB_LISTTYPE.LLT_CLASSES; return true; case ObjectListKind.Types: categoryField = (uint)_LIB_LISTTYPE.LLT_MEMBERS; if ((_flags & (Helpers.LLF_SEARCH_EXPAND_MEMBERS | Helpers.LLF_SEARCH_WITH_EXPANSION)) == 0) { categoryField |= (uint)_LIB_LISTTYPE.LLT_HIERARCHY; } return true; } categoryField = 0; return false; } private bool TryGetClassAccess(uint index, out uint categoryField) { var typeListItem = (TypeListItem)GetListItem(index); switch (typeListItem.Accessibility) { case Accessibility.Private: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PRIVATE; return true; case Accessibility.Protected: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PROTECTED; return true; case Accessibility.Internal: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PACKAGE; return true; default: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PUBLIC; return true; } } private bool TryGetClassType(uint index, out uint categoryField) { var typeListItem = (TypeListItem)GetListItem(index); switch (typeListItem.Kind) { case TypeKind.Interface: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_INTERFACE; return true; case TypeKind.Struct: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_STRUCT; return true; case TypeKind.Enum: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_ENUM; return true; case TypeKind.Delegate: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_DELEGATE; return true; case TypeKind.Class: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_CLASS; return true; case TypeKind.Module: categoryField = (uint)_LIBCAT_CLASSTYPE.LCCT_MODULE; return true; default: Debug.Fail("Unexpected type kind: " + typeListItem.Kind.ToString()); categoryField = 0; return false; } } private bool TryGetMemberInheritance(uint index, out uint categoryField) { var memberListItem = (MemberListItem)GetListItem(index); if (memberListItem.IsInherited) { categoryField = (uint)_LIBCAT_MEMBERINHERITANCE.LCMI_INHERITED; } else { categoryField = (uint)_LIBCAT_MEMBERINHERITANCE.LCMI_IMMEDIATE; } return true; } private bool TryGetMemberAccess(uint index, out uint categoryField) { var memberListItem = (MemberListItem)GetListItem(index); switch (memberListItem.Accessibility) { case Accessibility.Private: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PRIVATE; return true; case Accessibility.Protected: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PROTECTED; return true; case Accessibility.Internal: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PACKAGE; return true; default: categoryField = (uint)_LIBCAT_MEMBERACCESS.LCMA_PUBLIC; return true; } } private bool TryGetMemberType(uint index, out uint categoryField) { var memberListItem = (MemberListItem)GetListItem(index); switch (memberListItem.Kind) { case MemberKind.Constant: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_CONSTANT; return true; case MemberKind.EnumMember: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_ENUMITEM; return true; case MemberKind.Event: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_EVENT; return true; case MemberKind.Field: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_FIELD; return true; case MemberKind.Method: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_METHOD; return true; case MemberKind.Operator: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_OPERATOR; return true; case MemberKind.Property: categoryField = (uint)_LIBCAT_MEMBERTYPE.LCMT_PROPERTY; return true; default: Debug.Fail("Unexpected member kind: " + memberListItem.Kind.ToString()); categoryField = 0; return false; } } private bool TryGetPhysicalContainerType(uint index, out uint categoryField) { var listItem = GetListItem(index); switch (listItem.ParentListKind) { case ObjectListKind.Projects: categoryField = (uint)_LIBCAT_PHYSICALCONTAINERTYPE.LCPT_PROJECT; return true; case ObjectListKind.References: categoryField = (uint)_LIBCAT_PHYSICALCONTAINERTYPE.LCPT_PROJECTREFERENCE; return true; } categoryField = 0; return false; } private bool TryGetVisibility(uint index, out uint categoryField) { var item = GetListItem(index); categoryField = item.IsHidden ? (uint)_LIBCAT_VISIBILITY.LCV_HIDDEN : (uint)_LIBCAT_VISIBILITY.LCV_VISIBLE; return true; } protected override bool TryGetCategoryField(uint index, int category, out uint categoryField) { switch (category) { case (int)LIB_CATEGORY.LC_LISTTYPE: return TryGetListType(out categoryField); case (int)_LIB_CATEGORY2.LC_MEMBERINHERITANCE: return TryGetMemberInheritance(index, out categoryField); case (int)LIB_CATEGORY.LC_MEMBERACCESS: return TryGetMemberAccess(index, out categoryField); case (int)LIB_CATEGORY.LC_MEMBERTYPE: return TryGetMemberType(index, out categoryField); case (int)LIB_CATEGORY.LC_CLASSACCESS: return TryGetClassAccess(index, out categoryField); case (int)LIB_CATEGORY.LC_CLASSTYPE: return TryGetClassType(index, out categoryField); case (int)_LIB_CATEGORY2.LC_HIERARCHYTYPE: if (_kind == ObjectListKind.Hierarchy) { categoryField = this.ParentKind == ObjectListKind.Projects ? (uint)_LIBCAT_HIERARCHYTYPE.LCHT_PROJECTREFERENCES : (uint)_LIBCAT_HIERARCHYTYPE.LCHT_BASESANDINTERFACES; } else { categoryField = (uint)_LIBCAT_HIERARCHYTYPE.LCHT_UNKNOWN; } return true; case (int)LIB_CATEGORY.LC_NODETYPE: categoryField = 0; return false; case (int)_LIB_CATEGORY2.LC_PHYSICALCONTAINERTYPE: return TryGetPhysicalContainerType(index, out categoryField); case (int)LIB_CATEGORY.LC_VISIBILITY: return TryGetVisibility(index, out categoryField); } throw new NotImplementedException(); } protected override void GetDisplayData(uint index, ref VSTREEDISPLAYDATA data) { var item = GetListItem(index); data.Image = item.GlyphIndex; data.SelectedImage = item.GlyphIndex; if (item.IsHidden) { data.State |= (uint)_VSTREEDISPLAYSTATE.TDS_GRAYTEXT; } } protected override bool GetExpandable(uint index, uint listTypeExcluded) { switch (_kind) { case ObjectListKind.Hierarchy: case ObjectListKind.Namespaces: case ObjectListKind.Projects: case ObjectListKind.References: return true; case ObjectListKind.BaseTypes: case ObjectListKind.Types: return IsExpandableType(index); } return false; } private bool IsExpandableType(uint index) { if (GetListItem(index) is not TypeListItem typeListItem) { return false; } var compilation = typeListItem.GetCompilation(this.LibraryManager.Workspace); if (compilation == null) { return false; } var typeSymbol = typeListItem.ResolveTypedSymbol(compilation); // We never show base types for System.Object if (typeSymbol.SpecialType == SpecialType.System_Object) { return false; } if (typeSymbol.TypeKind == TypeKind.Module) { return false; } if (typeSymbol.TypeKind == TypeKind.Interface && typeSymbol.Interfaces.IsEmpty) { return false; } if (typeSymbol.BaseType == null) { return false; } return true; } protected override uint GetItemCount() => (uint)_items.Length; protected override IVsSimpleObjectList2 GetList(uint index, uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch) { var listItem = GetListItem(index); // We need to do a little massaging of the list type and parent item in a couple of cases. switch (_kind) { case ObjectListKind.Hierarchy: // LLT_USESCLASSES is for displaying base classes and interfaces // LLF_PROJREF is for displaying project references listType = listType == (uint)_LIB_LISTTYPE.LLT_CLASSES ? (uint)_LIB_LISTTYPE.LLT_USESCLASSES : Helpers.LLT_PROJREF; // Use the parent of this list as the parent of the new list. listItem = listItem.ParentList._parentListItem; break; case ObjectListKind.BaseTypes: if (listType == (uint)_LIB_LISTTYPE.LLT_CLASSES) { listType = (uint)_LIB_LISTTYPE.LLT_USESCLASSES; } break; } var listKind = Helpers.ListTypeToObjectListKind(listType); if (Helpers.IsFindSymbol(flags)) { var project = this.LibraryManager.GetProject(listItem.ProjectId); if (project == null) { return null; } var lookInReferences = (flags & ((uint)_VSOBSEARCHOPTIONS.VSOBSO_LOOKINREFS | (uint)_VSOBSEARCHOPTIONS2.VSOBSO_LISTREFERENCES)) != 0; var projectAndAssemblySet = this.LibraryManager.GetAssemblySet(project, lookInReferences, CancellationToken.None); return this.LibraryManager.GetSearchList(listKind, flags, pobSrch, projectAndAssemblySet); } var compilation = listItem.GetCompilation(this.LibraryManager.Workspace); if (compilation == null) { return null; } switch (listKind) { case ObjectListKind.Types: return new ObjectList(ObjectListKind.Types, flags, this, listItem, _manager, this.LibraryManager.GetTypeListItems(listItem, compilation)); case ObjectListKind.Hierarchy: return new ObjectList(ObjectListKind.Hierarchy, flags, this, listItem, _manager, this.LibraryManager.GetFolderListItems(listItem, compilation)); case ObjectListKind.Namespaces: return new ObjectList(ObjectListKind.Namespaces, flags, this, listItem, _manager, this.LibraryManager.GetNamespaceListItems(listItem, compilation)); case ObjectListKind.Members: return new ObjectList(ObjectListKind.Members, flags, this, listItem, _manager, this.LibraryManager.GetMemberListItems(listItem, compilation)); case ObjectListKind.References: return new ObjectList(ObjectListKind.References, flags, this, listItem, _manager, this.LibraryManager.GetReferenceListItems(listItem, compilation)); case ObjectListKind.BaseTypes: return new ObjectList(ObjectListKind.BaseTypes, flags, this, listItem, _manager, this.LibraryManager.GetBaseTypeListItems(listItem, compilation)); } throw new NotImplementedException(); } protected override object GetBrowseObject(uint index) { if (GetListItem(index) is SymbolListItem symbolListItem) { return this.LibraryManager.Workspace.GetBrowseObject(symbolListItem); } return base.GetBrowseObject(index); } protected override bool SupportsNavInfo { get { return true; } } protected override IVsNavInfo GetNavInfo(uint index) { var listItem = GetListItem(index); if (listItem == null) { return null; } if (listItem is ProjectListItem projectListItem) { var project = this.LibraryManager.GetProject(projectListItem.ProjectId); if (project != null) { return this.LibraryManager.LibraryService.NavInfoFactory.CreateForProject(project); } } if (listItem is ReferenceListItem referenceListItem) { return this.LibraryManager.LibraryService.NavInfoFactory.CreateForReference(referenceListItem.MetadataReference); } if (listItem is SymbolListItem symbolListItem) { return this.LibraryManager.GetNavInfo(symbolListItem, useExpandedHierarchy: IsClassView()); } return null; } protected override IVsNavInfoNode GetNavInfoNode(uint index) { var listItem = GetListItem(index); var name = listItem.DisplayText; var type = Helpers.ObjectListKindToListType(_kind); if (type == (uint)_LIB_LISTTYPE.LLT_USESCLASSES) { type = (uint)_LIB_LISTTYPE.LLT_CLASSES; } else if (type == Helpers.LLT_PROJREF) { type = (uint)_LIB_LISTTYPE.LLT_PACKAGE; } return new NavInfoNode(name, type); } protected override bool TryLocateNavInfoNode(IVsNavInfoNode pNavInfoNode, out uint index) { var itemCount = GetItemCount(); index = 0xffffffffu; if (ErrorHandler.Failed(pNavInfoNode.get_Name(out var matchName))) { return false; } if (ErrorHandler.Failed(pNavInfoNode.get_Type(out _))) { return false; } var longestMatchedName = string.Empty; for (uint i = 0; i < itemCount; i++) { var name = GetText(i, VSTREETEXTOPTIONS.TTO_DISPLAYTEXT); if (_kind is ObjectListKind.Types or ObjectListKind.Namespaces or ObjectListKind.Members) { if (string.Equals(matchName, name, StringComparison.Ordinal)) { index = i; break; } } else { if (string.Equals(matchName, name, StringComparison.Ordinal)) { index = i; break; } else if (_kind == ObjectListKind.Projects) { if (matchName.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0) { if (longestMatchedName.Length < name.Length) { longestMatchedName = name; index = i; } } } } } return index != 0xffffffffu; } protected override bool SupportsDescription { get { return true; } } protected override bool TryFillDescription(uint index, _VSOBJDESCOPTIONS options, IVsObjectBrowserDescription3 description) { var listItem = GetListItem(index); return this.LibraryManager.TryFillDescription(listItem, description, options); } protected override bool TryGetProperty(uint index, _VSOBJLISTELEMPROPID propertyId, out object pvar) { pvar = null; var listItem = GetListItem(index); if (listItem == null) { return false; } switch (propertyId) { case _VSOBJLISTELEMPROPID.VSOBJLISTELEMPROPID_FULLNAME: pvar = listItem.FullNameText; return true; case _VSOBJLISTELEMPROPID.VSOBJLISTELEMPROPID_HELPKEYWORD: if (listItem is SymbolListItem symbolListItem) { var project = this.LibraryManager.Workspace.CurrentSolution.GetProject(symbolListItem.ProjectId); if (project != null) { var compilation = project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult_ObjectBrowser(CancellationToken.None); var symbol = symbolListItem.ResolveSymbol(compilation); if (symbol != null) { var helpContextService = project.LanguageServices.GetService<IHelpContextService>(); pvar = helpContextService.FormatSymbol(symbol); return true; } } } return false; } return false; } protected override bool TryCountSourceItems(uint index, out IVsHierarchy hierarchy, out uint itemid, out uint items) { hierarchy = null; itemid = 0; items = 0; var listItem = GetListItem(index); if (listItem == null) { return false; } hierarchy = this.LibraryManager.Workspace.GetHierarchy(listItem.ProjectId); if (listItem is ProjectListItem) { itemid = (uint)VSConstants.VSITEMID.Root; items = 1; return true; } else if (listItem is SymbolListItem) { // TODO: Get itemid items = 1; return true; } return false; } protected override string GetText(uint index, VSTREETEXTOPTIONS tto) => GetDisplayText(index, tto); protected override string GetTipText(uint index, VSTREETOOLTIPTYPE eTipType) => null; protected override async Task GoToSourceAsync(uint index, VSOBJGOTOSRCTYPE srcType) { try { using var token = _manager.AsynchronousOperationListener.BeginAsyncOperation(nameof(GoToSourceAsync)); using var context = _manager.OperationExecutor.BeginExecute(ServicesVSResources.IntelliSense, EditorFeaturesResources.Navigating, allowCancellation: true, showProgress: false); var cancellationToken = context.UserCancellationToken; if (srcType == VSOBJGOTOSRCTYPE.GS_DEFINITION && GetListItem(index) is SymbolListItem symbolItem && symbolItem.SupportsGoToDefinition) { var project = this.LibraryManager.Workspace.CurrentSolution.GetProject(symbolItem.ProjectId); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var symbol = symbolItem.ResolveSymbol(compilation); await this.LibraryManager.Workspace.TryGoToDefinitionAsync(symbol, project, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) { } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { } } protected override uint GetUpdateCounter() { switch (_kind) { case ObjectListKind.Projects: case ObjectListKind.References: return _manager.PackageVersion; case ObjectListKind.BaseTypes: case ObjectListKind.Namespaces: case ObjectListKind.Types: return _manager.ClassVersion; case ObjectListKind.Members: return _manager.MembersVersion; case ObjectListKind.Hierarchy: return _manager.ClassVersion | _manager.MembersVersion; default: Debug.Fail("Unsupported object list kind: " + _kind.ToString()); throw new InvalidOperationException(); } } protected override bool TryGetContextMenu(uint index, out Guid menuGuid, out int menuId) { if (GetListItem(index) == null) { menuGuid = Guid.Empty; menuId = 0; return false; } menuGuid = VsMenus.guidSHLMainMenu; // from vsshlids.h const int IDM_VS_CTXT_CV_PROJECT = 0x0432; const int IDM_VS_CTXT_CV_ITEM = 0x0433; const int IDM_VS_CTXT_CV_GROUPINGFOLDER = 0x0435; const int IDM_VS_CTXT_CV_MEMBER = 0x0438; switch (_kind) { case ObjectListKind.Projects: menuId = IDM_VS_CTXT_CV_PROJECT; break; case ObjectListKind.Members: menuId = IDM_VS_CTXT_CV_MEMBER; break; case ObjectListKind.Hierarchy: menuId = IDM_VS_CTXT_CV_GROUPINGFOLDER; break; default: menuId = IDM_VS_CTXT_CV_ITEM; break; } return true; } protected override bool SupportsBrowseContainers { get { return true; } } protected override bool TryFindBrowseContainer(VSCOMPONENTSELECTORDATA data, out uint index) { index = 0; var count = GetItemCount(); for (uint i = 0; i < count; i++) { var listItem = GetListItem(i); if (data.type == VSCOMPONENTTYPE.VSCOMPONENTTYPE_ComPlus) { if (listItem is not ReferenceListItem referenceListItem) { continue; } if (referenceListItem.MetadataReference is not PortableExecutableReference metadataReference) { continue; } if (string.Equals(data.bstrFile, metadataReference.FilePath, StringComparison.OrdinalIgnoreCase)) { index = i; return true; } } else { Debug.Assert(data.type == VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project); var hierarchy = this.LibraryManager.Workspace.GetHierarchy(listItem.ProjectId); if (hierarchy == null) { continue; } if (this.LibraryManager.ServiceProvider.GetService(typeof(SVsSolution)) is not IVsSolution vsSolution) { return false; } if (ErrorHandler.Failed(vsSolution.GetProjrefOfProject(hierarchy, out var projectRef))) { return false; } if (data.bstrProjRef == projectRef) { index = i; return true; } } } return false; } protected override bool TryGetBrowseContainerData(uint index, ref VSCOMPONENTSELECTORDATA data) { var listItem = GetListItem(index); if (listItem is ProjectListItem projectListItem) { var hierarchy = this.LibraryManager.Workspace.GetHierarchy(projectListItem.ProjectId); if (hierarchy == null) { return false; } if (this.LibraryManager.ServiceProvider.GetService(typeof(SVsSolution)) is not IVsSolution vsSolution) { return false; } if (ErrorHandler.Failed(vsSolution.GetProjrefOfProject(hierarchy, out var projectRef))) { return false; } var project = this.LibraryManager.Workspace.CurrentSolution.GetProject(projectListItem.ProjectId); if (project == null) { return false; } data.bstrFile = project.FilePath; data.bstrProjRef = projectRef; data.bstrTitle = projectListItem.DisplayText; data.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project; } else { if (listItem is not ReferenceListItem referenceListItem) { return false; } if (referenceListItem.MetadataReference is not PortableExecutableReference portableExecutableReference) { return false; } var assemblyIdentity = AssemblyIdentityUtils.TryGetAssemblyIdentity(portableExecutableReference.FilePath); if (assemblyIdentity == null) { return false; } data.bstrFile = portableExecutableReference.FilePath; data.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_ComPlus; data.wFileMajorVersion = (ushort)assemblyIdentity.Version.Major; data.wFileMinorVersion = (ushort)assemblyIdentity.Version.Minor; data.wFileBuildNumber = (ushort)assemblyIdentity.Version.Build; data.wFileRevisionNumber = (ushort)assemblyIdentity.Version.Revision; } return true; } public ObjectListKind Kind { get { return _kind; } } public ObjectListKind ParentKind { get { return _parentList != null ? _parentList.Kind : ObjectListKind.None; } } public ObjectListItem ParentListItem { get { return _parentListItem; } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/CSharp/Portable/CodeRefactorings/LambdaSimplifier/LambdaSimplifierCodeRefactoringProvider.Rewriter.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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.LambdaSimplifier { internal partial class LambdaSimplifierCodeRefactoringProvider { private class Rewriter : CSharpSyntaxRewriter { private readonly SemanticDocument _document; private readonly Func<SyntaxNode, bool> _predicate; private readonly CancellationToken _cancellationToken; public Rewriter( SemanticDocument document, Func<SyntaxNode, bool> predicate, CancellationToken cancellationToken) { _document = document; _predicate = predicate; _cancellationToken = cancellationToken; } private ExpressionSyntax SimplifyInvocation(InvocationExpressionSyntax invocation) { var expression = invocation.Expression; if (expression is MemberAccessExpressionSyntax memberAccess) { var symbolMap = SemanticMap.From(_document.SemanticModel, memberAccess.Expression, _cancellationToken); var anySideEffects = symbolMap.AllReferencedSymbols.Any(s => s.Kind is SymbolKind.Method or SymbolKind.Property); if (anySideEffects) { var annotation = WarningAnnotation.Create(CSharpFeaturesResources.Warning_Expression_may_change_code_meaning); expression = expression.ReplaceNode(memberAccess.Expression, memberAccess.Expression.WithAdditionalAnnotations(annotation)); } } return expression.Parenthesize() .WithAdditionalAnnotations(Formatter.Annotation); } public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { if (_predicate(node) && CanSimplify(_document, node, _cancellationToken)) { var invocation = TryGetInvocationExpression(node.Body); if (invocation != null) { return SimplifyInvocation(invocation); } } return base.VisitSimpleLambdaExpression(node); } public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { if (_predicate(node) && CanSimplify(_document, node, _cancellationToken)) { var invocation = TryGetInvocationExpression(node.Body); if (invocation != null) { return SimplifyInvocation(invocation); } } return base.VisitParenthesizedLambdaExpression(node); } } } }
// 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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.LambdaSimplifier { internal partial class LambdaSimplifierCodeRefactoringProvider { private class Rewriter : CSharpSyntaxRewriter { private readonly SemanticDocument _document; private readonly Func<SyntaxNode, bool> _predicate; private readonly CancellationToken _cancellationToken; public Rewriter( SemanticDocument document, Func<SyntaxNode, bool> predicate, CancellationToken cancellationToken) { _document = document; _predicate = predicate; _cancellationToken = cancellationToken; } private ExpressionSyntax SimplifyInvocation(InvocationExpressionSyntax invocation) { var expression = invocation.Expression; if (expression is MemberAccessExpressionSyntax memberAccess) { var symbolMap = SemanticMap.From(_document.SemanticModel, memberAccess.Expression, _cancellationToken); var anySideEffects = symbolMap.AllReferencedSymbols.Any(s => s.Kind is SymbolKind.Method or SymbolKind.Property); if (anySideEffects) { var annotation = WarningAnnotation.Create(CSharpFeaturesResources.Warning_Expression_may_change_code_meaning); expression = expression.ReplaceNode(memberAccess.Expression, memberAccess.Expression.WithAdditionalAnnotations(annotation)); } } return expression.Parenthesize() .WithAdditionalAnnotations(Formatter.Annotation); } public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { if (_predicate(node) && CanSimplify(_document, node, _cancellationToken)) { var invocation = TryGetInvocationExpression(node.Body); if (invocation != null) { return SimplifyInvocation(invocation); } } return base.VisitSimpleLambdaExpression(node); } public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { if (_predicate(node) && CanSimplify(_document, node, _cancellationToken)) { var invocation = TryGetInvocationExpression(node.Body); if (invocation != null) { return SimplifyInvocation(invocation); } } return base.VisitParenthesizedLambdaExpression(node); } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/CSharp/Impl/CodeModel/Extenders/ExtensionMethodExtender.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; using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders { [ComVisible(true)] [ComDefaultInterface(typeof(ICSExtensionMethodExtender))] public class ExtensionMethodExtender : ICSExtensionMethodExtender { internal static ICSExtensionMethodExtender Create(bool isExtension) { var result = new ExtensionMethodExtender(isExtension); return (ICSExtensionMethodExtender)ComAggregate.CreateAggregatedObject(result); } private readonly bool _isExtension; private ExtensionMethodExtender(bool isExtension) => _isExtension = isExtension; public bool IsExtension { get { return _isExtension; } } } }
// 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; using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders { [ComVisible(true)] [ComDefaultInterface(typeof(ICSExtensionMethodExtender))] public class ExtensionMethodExtender : ICSExtensionMethodExtender { internal static ICSExtensionMethodExtender Create(bool isExtension) { var result = new ExtensionMethodExtender(isExtension); return (ICSExtensionMethodExtender)ComAggregate.CreateAggregatedObject(result); } private readonly bool _isExtension; private ExtensionMethodExtender(bool isExtension) => _isExtension = isExtension; public bool IsExtension { get { return _isExtension; } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Workspaces/Core/Portable/Diagnostics/WellKnownDiagnosticPropertyNames.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.Diagnostics { internal static class WellKnownDiagnosticPropertyNames { /// <summary> /// Predefined name of diagnostic property which shows in what compilation stage the diagnostic is created. /// </summary> public const string Origin = nameof(Origin); } }
// 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.Diagnostics { internal static class WellKnownDiagnosticPropertyNames { /// <summary> /// Predefined name of diagnostic property which shows in what compilation stage the diagnostic is created. /// </summary> public const string Origin = nameof(Origin); } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/CSharp/Portable/Symbols/EventSymbol.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; using System.Diagnostics.CodeAnalysis; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an event. /// </summary> internal abstract partial class EventSymbol : Symbol { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! internal EventSymbol() { } /// <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 EventSymbol OriginalDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// The type of the event along with its annotations. /// </summary> public abstract TypeWithAnnotations TypeWithAnnotations { get; } /// <summary> /// The type of the event. /// </summary> public TypeSymbol Type => TypeWithAnnotations.Type; /// <summary> /// The 'add' accessor of the event. Null only in error scenarios. /// </summary> public abstract MethodSymbol? AddMethod { get; } /// <summary> /// The 'remove' accessor of the event. Null only in error scenarios. /// </summary> public abstract MethodSymbol? RemoveMethod { get; } internal bool HasAssociatedField { get { return (object?)this.AssociatedField != null; } } /// <summary> /// Returns true if this symbol requires an instance reference as the implicit receiver. This is false if the symbol is static. /// </summary> public virtual bool RequiresInstanceReceiver => !IsStatic; /// <summary> /// True if this is a Windows Runtime-style event. /// /// A normal C# event, "event D E", has accessors /// void add_E(D d) /// void remove_E(D d) /// /// A Windows Runtime event, "event D E", has accessors /// EventRegistrationToken add_E(D d) /// void remove_E(EventRegistrationToken t) /// </summary> public abstract bool IsWindowsRuntimeEvent { get; } /// <summary> /// True if the event itself is excluded from code coverage instrumentation. /// True for source events marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>. /// </summary> internal virtual bool IsDirectlyExcludedFromCodeCoverage { get => false; } /// <summary> /// True if this symbol has a special name (metadata flag SpecialName is set). /// </summary> internal abstract bool HasSpecialName { get; } /// <summary> /// Gets the attributes on event's associated field, if any. /// Returns an empty <see cref="ImmutableArray&lt;AttributeData&gt;"/> if /// there are no attributes. /// </summary> /// <remarks> /// This publicly exposes the attributes of the internal backing field. /// </remarks> public ImmutableArray<CSharpAttributeData> GetFieldAttributes() { return (object?)this.AssociatedField == null ? ImmutableArray<CSharpAttributeData>.Empty : this.AssociatedField.GetAttributes(); } internal virtual FieldSymbol? AssociatedField { get { return null; } } /// <summary> /// Returns the overridden event, or null. /// </summary> public EventSymbol? OverriddenEvent { get { if (this.IsOverride) { if (IsDefinition) { return (EventSymbol)OverriddenOrHiddenMembers.GetOverriddenMember(); } return (EventSymbol)OverriddenOrHiddenMembersResult.GetOverriddenMember(this, OriginalDefinition.OverriddenEvent); } return null; } } internal virtual OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { return this.MakeOverriddenOrHiddenMembers(); } } internal bool HidesBaseEventsByName { get { MethodSymbol? accessor = AddMethod ?? RemoveMethod; return (object?)accessor != null && accessor.HidesBaseMethodsByName; } } internal EventSymbol GetLeastOverriddenEvent(NamedTypeSymbol? accessingTypeOpt) { accessingTypeOpt = accessingTypeOpt?.OriginalDefinition; EventSymbol e = this; while (e.IsOverride && !e.HidesBaseEventsByName) { // NOTE: We might not be able to access the overridden event. For example, // // .assembly A // { // InternalsVisibleTo("B") // public class A { internal virtual event Action E { add; remove; } } // } // // .assembly B // { // InternalsVisibleTo("C") // public class B : A { internal override event Action E { add; remove; } } // } // // .assembly C // { // public class C : B { ... new B().E += null ... } // A.E is not accessible from here // } // // See InternalsVisibleToAndStrongNameTests: IvtVirtualCall1, IvtVirtualCall2, IvtVirtual_ParamsAndDynamic. EventSymbol? overridden = e.OverriddenEvent; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if ((object?)overridden == null || (accessingTypeOpt is { } && !AccessCheck.IsSymbolAccessible(overridden, accessingTypeOpt, ref discardedUseSiteInfo))) { break; } e = overridden; } return e; } /// <summary> /// Source: Was the member name qualified with a type name? /// Metadata: Is the member an explicit implementation? /// </summary> /// <remarks> /// Will not always agree with ExplicitInterfaceImplementations.Any() /// (e.g. if binding of the type part of the name fails). /// </remarks> internal virtual bool IsExplicitInterfaceImplementation { get { return ExplicitInterfaceImplementations.Any(); } } /// <summary> /// Returns interface events explicitly implemented by this event. /// </summary> /// <remarks> /// Events imported from metadata can explicitly implement more than one event. /// </remarks> public abstract ImmutableArray<EventSymbol> ExplicitInterfaceImplementations { get; } /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Event; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitEvent(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitEvent(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitEvent(this); } internal EventSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition)); Debug.Assert(newOwner.IsDefinition || newOwner is SubstitutedNamedTypeSymbol); return newOwner.IsDefinition ? this : new SubstitutedEventSymbol((newOwner as SubstitutedNamedTypeSymbol)!, this); } internal abstract bool MustCallMethodsDirectly { get; } #region Use-Site Diagnostics internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { if (this.IsDefinition) { return new UseSiteInfo<AssemblySymbol>(PrimaryDependency); } return this.OriginalDefinition.GetUseSiteInfo(); } internal bool CalculateUseSiteDiagnostic(ref UseSiteInfo<AssemblySymbol> result) { Debug.Assert(this.IsDefinition); // Check event type. if (DeriveUseSiteInfoFromType(ref result, this.TypeWithAnnotations, AllowedRequiredModifierType.None)) { return true; } if (this.ContainingModule.HasUnifiedReferences) { // If the member is in an assembly with unified references, // we check if its definition depends on a type from a unified reference. HashSet<TypeSymbol>? unificationCheckedTypes = null; DiagnosticInfo? diagnosticInfo = result.DiagnosticInfo; if (this.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref diagnosticInfo, this, ref unificationCheckedTypes)) { result = result.AdjustDiagnosticInfo(diagnosticInfo); return true; } result = result.AdjustDiagnosticInfo(diagnosticInfo); } return false; } protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BindToBogus; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo? info = GetUseSiteInfo().DiagnosticInfo; return (object?)info != null && info.Code == (int)ErrorCode.ERR_BindToBogus; } } #endregion protected sealed override ISymbol CreateISymbol() { return new PublicModel.EventSymbol(this); } #region Equality public override bool Equals(Symbol? obj, TypeCompareKind compareKind) { EventSymbol? other = obj as EventSymbol; if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } // This checks if the events have the same definition and the type parameters on the containing types have been // substituted in the same way. return TypeSymbol.Equals(this.ContainingType, other.ContainingType, compareKind) && ReferenceEquals(this.OriginalDefinition, other.OriginalDefinition); } public override int GetHashCode() { int hash = 1; hash = Hash.Combine(this.ContainingType, hash); hash = Hash.Combine(this.Name, hash); return hash; } #endregion Equality } }
// 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; using System.Diagnostics.CodeAnalysis; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an event. /// </summary> internal abstract partial class EventSymbol : Symbol { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! internal EventSymbol() { } /// <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 EventSymbol OriginalDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// The type of the event along with its annotations. /// </summary> public abstract TypeWithAnnotations TypeWithAnnotations { get; } /// <summary> /// The type of the event. /// </summary> public TypeSymbol Type => TypeWithAnnotations.Type; /// <summary> /// The 'add' accessor of the event. Null only in error scenarios. /// </summary> public abstract MethodSymbol? AddMethod { get; } /// <summary> /// The 'remove' accessor of the event. Null only in error scenarios. /// </summary> public abstract MethodSymbol? RemoveMethod { get; } internal bool HasAssociatedField { get { return (object?)this.AssociatedField != null; } } /// <summary> /// Returns true if this symbol requires an instance reference as the implicit receiver. This is false if the symbol is static. /// </summary> public virtual bool RequiresInstanceReceiver => !IsStatic; /// <summary> /// True if this is a Windows Runtime-style event. /// /// A normal C# event, "event D E", has accessors /// void add_E(D d) /// void remove_E(D d) /// /// A Windows Runtime event, "event D E", has accessors /// EventRegistrationToken add_E(D d) /// void remove_E(EventRegistrationToken t) /// </summary> public abstract bool IsWindowsRuntimeEvent { get; } /// <summary> /// True if the event itself is excluded from code coverage instrumentation. /// True for source events marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>. /// </summary> internal virtual bool IsDirectlyExcludedFromCodeCoverage { get => false; } /// <summary> /// True if this symbol has a special name (metadata flag SpecialName is set). /// </summary> internal abstract bool HasSpecialName { get; } /// <summary> /// Gets the attributes on event's associated field, if any. /// Returns an empty <see cref="ImmutableArray&lt;AttributeData&gt;"/> if /// there are no attributes. /// </summary> /// <remarks> /// This publicly exposes the attributes of the internal backing field. /// </remarks> public ImmutableArray<CSharpAttributeData> GetFieldAttributes() { return (object?)this.AssociatedField == null ? ImmutableArray<CSharpAttributeData>.Empty : this.AssociatedField.GetAttributes(); } internal virtual FieldSymbol? AssociatedField { get { return null; } } /// <summary> /// Returns the overridden event, or null. /// </summary> public EventSymbol? OverriddenEvent { get { if (this.IsOverride) { if (IsDefinition) { return (EventSymbol)OverriddenOrHiddenMembers.GetOverriddenMember(); } return (EventSymbol)OverriddenOrHiddenMembersResult.GetOverriddenMember(this, OriginalDefinition.OverriddenEvent); } return null; } } internal virtual OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { return this.MakeOverriddenOrHiddenMembers(); } } internal bool HidesBaseEventsByName { get { MethodSymbol? accessor = AddMethod ?? RemoveMethod; return (object?)accessor != null && accessor.HidesBaseMethodsByName; } } internal EventSymbol GetLeastOverriddenEvent(NamedTypeSymbol? accessingTypeOpt) { accessingTypeOpt = accessingTypeOpt?.OriginalDefinition; EventSymbol e = this; while (e.IsOverride && !e.HidesBaseEventsByName) { // NOTE: We might not be able to access the overridden event. For example, // // .assembly A // { // InternalsVisibleTo("B") // public class A { internal virtual event Action E { add; remove; } } // } // // .assembly B // { // InternalsVisibleTo("C") // public class B : A { internal override event Action E { add; remove; } } // } // // .assembly C // { // public class C : B { ... new B().E += null ... } // A.E is not accessible from here // } // // See InternalsVisibleToAndStrongNameTests: IvtVirtualCall1, IvtVirtualCall2, IvtVirtual_ParamsAndDynamic. EventSymbol? overridden = e.OverriddenEvent; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if ((object?)overridden == null || (accessingTypeOpt is { } && !AccessCheck.IsSymbolAccessible(overridden, accessingTypeOpt, ref discardedUseSiteInfo))) { break; } e = overridden; } return e; } /// <summary> /// Source: Was the member name qualified with a type name? /// Metadata: Is the member an explicit implementation? /// </summary> /// <remarks> /// Will not always agree with ExplicitInterfaceImplementations.Any() /// (e.g. if binding of the type part of the name fails). /// </remarks> internal virtual bool IsExplicitInterfaceImplementation { get { return ExplicitInterfaceImplementations.Any(); } } /// <summary> /// Returns interface events explicitly implemented by this event. /// </summary> /// <remarks> /// Events imported from metadata can explicitly implement more than one event. /// </remarks> public abstract ImmutableArray<EventSymbol> ExplicitInterfaceImplementations { get; } /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Event; } } /// <summary> /// Implements visitor pattern. /// </summary> internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitEvent(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitEvent(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitEvent(this); } internal EventSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition)); Debug.Assert(newOwner.IsDefinition || newOwner is SubstitutedNamedTypeSymbol); return newOwner.IsDefinition ? this : new SubstitutedEventSymbol((newOwner as SubstitutedNamedTypeSymbol)!, this); } internal abstract bool MustCallMethodsDirectly { get; } #region Use-Site Diagnostics internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { if (this.IsDefinition) { return new UseSiteInfo<AssemblySymbol>(PrimaryDependency); } return this.OriginalDefinition.GetUseSiteInfo(); } internal bool CalculateUseSiteDiagnostic(ref UseSiteInfo<AssemblySymbol> result) { Debug.Assert(this.IsDefinition); // Check event type. if (DeriveUseSiteInfoFromType(ref result, this.TypeWithAnnotations, AllowedRequiredModifierType.None)) { return true; } if (this.ContainingModule.HasUnifiedReferences) { // If the member is in an assembly with unified references, // we check if its definition depends on a type from a unified reference. HashSet<TypeSymbol>? unificationCheckedTypes = null; DiagnosticInfo? diagnosticInfo = result.DiagnosticInfo; if (this.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref diagnosticInfo, this, ref unificationCheckedTypes)) { result = result.AdjustDiagnosticInfo(diagnosticInfo); return true; } result = result.AdjustDiagnosticInfo(diagnosticInfo); } return false; } protected override int HighestPriorityUseSiteError { get { return (int)ErrorCode.ERR_BindToBogus; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo? info = GetUseSiteInfo().DiagnosticInfo; return (object?)info != null && info.Code == (int)ErrorCode.ERR_BindToBogus; } } #endregion protected sealed override ISymbol CreateISymbol() { return new PublicModel.EventSymbol(this); } #region Equality public override bool Equals(Symbol? obj, TypeCompareKind compareKind) { EventSymbol? other = obj as EventSymbol; if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } // This checks if the events have the same definition and the type parameters on the containing types have been // substituted in the same way. return TypeSymbol.Equals(this.ContainingType, other.ContainingType, compareKind) && ReferenceEquals(this.OriginalDefinition, other.OriginalDefinition); } public override int GetHashCode() { int hash = 1; hash = Hash.Combine(this.ContainingType, hash); hash = Hash.Combine(this.Name, hash); return hash; } #endregion Equality } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ExceptionLocalSymbol.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.Symbols; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class ExceptionLocalSymbol : PlaceholderLocalSymbol { private readonly string _getExceptionMethodName; internal ExceptionLocalSymbol(MethodSymbol method, string name, string displayName, TypeSymbol type, string getExceptionMethodName) : base(method, name, displayName, type) { _getExceptionMethodName = getExceptionMethodName; } internal override bool IsWritableVariable { get { return false; } } internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, DiagnosticBag diagnostics) { var method = GetIntrinsicMethod(compilation, _getExceptionMethodName); var call = BoundCall.Synthesized(syntax, receiverOpt: null, method: method); return ConvertToLocalType(compilation, call, this.Type, diagnostics); } } }
// 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.Symbols; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class ExceptionLocalSymbol : PlaceholderLocalSymbol { private readonly string _getExceptionMethodName; internal ExceptionLocalSymbol(MethodSymbol method, string name, string displayName, TypeSymbol type, string getExceptionMethodName) : base(method, name, displayName, type) { _getExceptionMethodName = getExceptionMethodName; } internal override bool IsWritableVariable { get { return false; } } internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, DiagnosticBag diagnostics) { var method = GetIntrinsicMethod(compilation, _getExceptionMethodName); var call = BoundCall.Synthesized(syntax, receiverOpt: null, method: method); return ConvertToLocalType(compilation, call, this.Type, diagnostics); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Server/VBCSCompilerTests/Extensions.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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal static class Extensions { public static Task ToTask(this WaitHandle handle, int? timeoutMilliseconds) { RegisteredWaitHandle registeredHandle = null; var tcs = new TaskCompletionSource<object>(); registeredHandle = ThreadPool.RegisterWaitForSingleObject( handle, (_, timeout) => { tcs.TrySetResult(null); if (registeredHandle is object) { registeredHandle.Unregister(waitObject: null); } }, null, timeoutMilliseconds ?? -1, executeOnlyOnce: true); return tcs.Task; } public static async Task WaitOneAsync(this WaitHandle handle, int? timeoutMilliseconds = null) => await handle.ToTask(timeoutMilliseconds); public static async ValueTask<T> TakeAsync<T>(this BlockingCollection<T> collection, TimeSpan? pollTimeSpan = null, CancellationToken cancellationToken = default) { var delay = pollTimeSpan ?? TimeSpan.FromSeconds(.25); do { if (collection.TryTake(out T value)) { return value; } await Task.Delay(delay, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); } while (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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal static class Extensions { public static Task ToTask(this WaitHandle handle, int? timeoutMilliseconds) { RegisteredWaitHandle registeredHandle = null; var tcs = new TaskCompletionSource<object>(); registeredHandle = ThreadPool.RegisterWaitForSingleObject( handle, (_, timeout) => { tcs.TrySetResult(null); if (registeredHandle is object) { registeredHandle.Unregister(waitObject: null); } }, null, timeoutMilliseconds ?? -1, executeOnlyOnce: true); return tcs.Task; } public static async Task WaitOneAsync(this WaitHandle handle, int? timeoutMilliseconds = null) => await handle.ToTask(timeoutMilliseconds); public static async ValueTask<T> TakeAsync<T>(this BlockingCollection<T> collection, TimeSpan? pollTimeSpan = null, CancellationToken cancellationToken = default) { var delay = pollTimeSpan ?? TimeSpan.FromSeconds(.25); do { if (collection.TryTake(out T value)) { return value; } await Task.Delay(delay, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); } while (true); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/Portable/SourceGeneration/Nodes/SharedInputNodes.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.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Holds input nodes that are shared between generators and always exist /// </summary> internal static class SharedInputNodes { public static readonly InputNode<Compilation> Compilation = new InputNode<Compilation>(b => ImmutableArray.Create(b.Compilation)); public static readonly InputNode<ParseOptions> ParseOptions = new InputNode<ParseOptions>(b => ImmutableArray.Create(b.DriverState.ParseOptions)); public static readonly InputNode<AdditionalText> AdditionalTexts = new InputNode<AdditionalText>(b => b.DriverState.AdditionalTexts); public static readonly InputNode<SyntaxTree> SyntaxTrees = new InputNode<SyntaxTree>(b => b.Compilation.SyntaxTrees.ToImmutableArray()); public static readonly InputNode<AnalyzerConfigOptionsProvider> AnalyzerConfigOptions = new InputNode<AnalyzerConfigOptionsProvider>(b => ImmutableArray.Create(b.DriverState.OptionsProvider)); public static readonly InputNode<MetadataReference> MetadataReferences = new InputNode<MetadataReference>(b => b.Compilation.ExternalReferences); } }
// 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.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Holds input nodes that are shared between generators and always exist /// </summary> internal static class SharedInputNodes { public static readonly InputNode<Compilation> Compilation = new InputNode<Compilation>(b => ImmutableArray.Create(b.Compilation)); public static readonly InputNode<ParseOptions> ParseOptions = new InputNode<ParseOptions>(b => ImmutableArray.Create(b.DriverState.ParseOptions)); public static readonly InputNode<AdditionalText> AdditionalTexts = new InputNode<AdditionalText>(b => b.DriverState.AdditionalTexts); public static readonly InputNode<SyntaxTree> SyntaxTrees = new InputNode<SyntaxTree>(b => b.Compilation.SyntaxTrees.ToImmutableArray()); public static readonly InputNode<AnalyzerConfigOptionsProvider> AnalyzerConfigOptions = new InputNode<AnalyzerConfigOptionsProvider>(b => ImmutableArray.Create(b.DriverState.OptionsProvider)); public static readonly InputNode<MetadataReference> MetadataReferences = new InputNode<MetadataReference>(b => b.Compilation.ExternalReferences); } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ULongKeywordRecommender.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; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ULongKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public ULongKeywordRecommender() : base(SyntaxKind.ULongKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_UInt64; } }
// 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; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ULongKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public ULongKeywordRecommender() : base(SyntaxKind.ULongKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_UInt64; } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionDefinition.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.CodeStyle; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { [NonDefaultable] internal readonly struct OptionDefinition : IEquatable<OptionDefinition> { /// <summary> /// Feature this option is associated with. /// </summary> public string Feature { get; } /// <summary> /// Optional group/sub-feature for this option. /// </summary> internal OptionGroup Group { get; } /// <summary> /// The name of the option. /// </summary> public string Name { get; } /// <summary> /// The default value of the option. /// </summary> public object? DefaultValue { get; } /// <summary> /// The type of the option value. /// </summary> public Type Type { get; } /// <summary> /// Flag indicating if this is a per-language option or a language specific option. /// </summary> public bool IsPerLanguage { get; } public OptionDefinition(string feature, OptionGroup group, string name, object? defaultValue, Type type, bool isPerLanguage) { if (string.IsNullOrWhiteSpace(feature)) { throw new ArgumentNullException(nameof(feature)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(nameof(name)); } this.Feature = feature; this.Group = group ?? throw new ArgumentNullException(nameof(group)); this.Name = name; this.DefaultValue = defaultValue; this.Type = type ?? throw new ArgumentNullException(nameof(type)); this.IsPerLanguage = isPerLanguage; } public override bool Equals(object? obj) { return obj is OptionDefinition key && Equals(key); } public bool Equals(OptionDefinition other) { var equals = this.Name == other.Name && this.Feature == other.Feature && this.Group == other.Group && this.IsPerLanguage == other.IsPerLanguage; // DefaultValue and Type can differ between different but equivalent implementations of "ICodeStyleOption". // So, we skip these fields for equality checks of code style options. if (equals && !(this.DefaultValue is ICodeStyleOption)) { equals = Equals(this.DefaultValue, other.DefaultValue) && this.Type == other.Type; } return equals; } public override int GetHashCode() { var hash = this.Feature.GetHashCode(); hash = unchecked((hash * (int)0xA5555529) + this.Group.GetHashCode()); hash = unchecked((hash * (int)0xA5555529) + this.Name.GetHashCode()); hash = unchecked((hash * (int)0xA5555529) + this.IsPerLanguage.GetHashCode()); // DefaultValue and Type can differ between different but equivalent implementations of "ICodeStyleOption". // So, we skip these fields for hash computation of code style options. if (this.DefaultValue is not ICodeStyleOption) { hash = unchecked((hash * (int)0xA5555529) + this.DefaultValue?.GetHashCode() ?? 0); hash = unchecked((hash * (int)0xA5555529) + this.Type.GetHashCode()); } return hash; } public override string ToString() => string.Format("{0} - {1}", this.Feature, this.Name); public static bool operator ==(OptionDefinition left, OptionDefinition right) => left.Equals(right); public static bool operator !=(OptionDefinition left, OptionDefinition right) => !left.Equals(right); } }
// 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.CodeStyle; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { [NonDefaultable] internal readonly struct OptionDefinition : IEquatable<OptionDefinition> { /// <summary> /// Feature this option is associated with. /// </summary> public string Feature { get; } /// <summary> /// Optional group/sub-feature for this option. /// </summary> internal OptionGroup Group { get; } /// <summary> /// The name of the option. /// </summary> public string Name { get; } /// <summary> /// The default value of the option. /// </summary> public object? DefaultValue { get; } /// <summary> /// The type of the option value. /// </summary> public Type Type { get; } /// <summary> /// Flag indicating if this is a per-language option or a language specific option. /// </summary> public bool IsPerLanguage { get; } public OptionDefinition(string feature, OptionGroup group, string name, object? defaultValue, Type type, bool isPerLanguage) { if (string.IsNullOrWhiteSpace(feature)) { throw new ArgumentNullException(nameof(feature)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(nameof(name)); } this.Feature = feature; this.Group = group ?? throw new ArgumentNullException(nameof(group)); this.Name = name; this.DefaultValue = defaultValue; this.Type = type ?? throw new ArgumentNullException(nameof(type)); this.IsPerLanguage = isPerLanguage; } public override bool Equals(object? obj) { return obj is OptionDefinition key && Equals(key); } public bool Equals(OptionDefinition other) { var equals = this.Name == other.Name && this.Feature == other.Feature && this.Group == other.Group && this.IsPerLanguage == other.IsPerLanguage; // DefaultValue and Type can differ between different but equivalent implementations of "ICodeStyleOption". // So, we skip these fields for equality checks of code style options. if (equals && !(this.DefaultValue is ICodeStyleOption)) { equals = Equals(this.DefaultValue, other.DefaultValue) && this.Type == other.Type; } return equals; } public override int GetHashCode() { var hash = this.Feature.GetHashCode(); hash = unchecked((hash * (int)0xA5555529) + this.Group.GetHashCode()); hash = unchecked((hash * (int)0xA5555529) + this.Name.GetHashCode()); hash = unchecked((hash * (int)0xA5555529) + this.IsPerLanguage.GetHashCode()); // DefaultValue and Type can differ between different but equivalent implementations of "ICodeStyleOption". // So, we skip these fields for hash computation of code style options. if (this.DefaultValue is not ICodeStyleOption) { hash = unchecked((hash * (int)0xA5555529) + this.DefaultValue?.GetHashCode() ?? 0); hash = unchecked((hash * (int)0xA5555529) + this.Type.GetHashCode()); } return hash; } public override string ToString() => string.Format("{0} - {1}", this.Feature, this.Name); public static bool operator ==(OptionDefinition left, OptionDefinition right) => left.Equals(right); public static bool operator !=(OptionDefinition left, OptionDefinition right) => !left.Equals(right); } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/EnumTests.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.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.Source { public class EnumTests : CSharpTestBase { // The value of first enumerator, and the value of each successive enumerator [Fact] public void ValueOfFirst() { var text = @"enum Suits { ValueA, ValueB, ValueC, ValueD } "; VerifyEnumsValue(text, "Suits", 0, 1, 2, 3); } // The value can be explicated initialized [Fact] public void ExplicateInit() { var text = @"public enum Suits { ValueA = -1, ValueB = 2, ValueC = 3, ValueD = 4, }; "; VerifyEnumsValue(text, "Suits", -1, 2, 3, 4); } // The value can be explicated and implicit initialized [Fact] public void MixedInit() { var text = @"public enum Suits { ValueA, ValueB = 10, ValueC, ValueD, }; "; VerifyEnumsValue(text, "Suits", 0, 10, 11, 12); } // Enumerator initializers must be of integral or enumeration type [Fact] public void OutOfUnderlyingRange() { var text = @"public enum Suits : byte { ValueA = ""3"", // Can't implicitly convert ValueB = 2.2, // Can't implicitly convert ValueC = 257 // Out of underlying range }; "; var comp = CreateCompilation(text); VerifyEnumsValue(comp, "Suits", SpecialType.System_Byte, null, (byte)2, null); comp.VerifyDiagnostics( // (3,10): error CS0029: Cannot implicitly convert type 'string' to 'byte' // ValueA = "3", // Can't implicitly convert Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""3""").WithArguments("string", "byte").WithLocation(3, 10), // (4,10): error CS0266: Cannot implicitly convert type 'double' to 'byte'. An explicit conversion exists (are you missing a cast?) // ValueB = 2.2, // Can't implicitly convert Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "2.2").WithArguments("double", "byte").WithLocation(4, 10), // (5,10): error CS0031: Constant value '257' cannot be converted to a 'byte' // ValueC = 257 // Out of underlying range Diagnostic(ErrorCode.ERR_ConstOutOfRange, "257").WithArguments("257", "byte").WithLocation(5, 10) ); text = @"enum Suits : short { a, b, c, d = -65536, e, f }"; comp = CreateCompilation(text); VerifyEnumsValue(comp, "Suits", SpecialType.System_Int16, (short)0, (short)1, (short)2, null, null, null); comp.VerifyDiagnostics( // (1,35): error CS0031: Constant value '-65536' cannot be converted to a 'short' // enum Suits : short { a, b, c, d = -65536, e, f } Diagnostic(ErrorCode.ERR_ConstOutOfRange, "-65536").WithArguments("-65536", "short").WithLocation(1, 35) ); } // Explicit associated value [Fact] public void ExplicitAssociated() { var text = @"class C<T> { const int field = 100; enum TestEnum { A, B = A, // another member C = D, // another member D = (byte)11, // type can be implicitly converted to underlying type E = 'a', // type can be implicitly converted to underlying type F = 3 + 5, // expression G = field, // const field TestEnum, // its own type name var, // contextual keyword T, // Type parameter }; enum EnumB { B = TestEnum.T }; } "; VerifyEnumsValue(text, "C.TestEnum", 0, 0, 11, 11, 97, 8, 100, 101, 102, 103); VerifyEnumsValue(text, "C.EnumB", 103); text = @"class c1 { public static int StaticField = 10; public static readonly int ReadonlyField = 100; enum EnumTest { A = StaticField, B = ReadonlyField }; } "; VerifyEnumsValue(text, "c1.EnumTest", null, null); } [WorkItem(539167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539167")] // No enum-body [Fact] public void CS1514ERR_LbraceExpected_NoEnumBody() { var text = @"enum Figure ;"; VerifyEnumsValue(text, "Figure"); var comp = CreateCompilation(text); // Same errors as parsing "class Name ;". DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_LbraceExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } [Fact] public void EnumEOFBeforeMembers() { var text = @"enum E"; VerifyEnumsValue(text, "E"); var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_LbraceExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } [Fact] public void EnumEOFWithinMembers() { var text = @"enum E {"; VerifyEnumsValue(text, "E"); var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } // No enum-body [Fact] public void NullEnumBody() { var text = @"enum Figure { }"; VerifyEnumsValue(text, "Figure"); } // No identifier [Fact] public void CS1001ERR_IdentifierExpected_NoIDForEnum() { var text = @"enum { One, Two, Three };"; var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_IdentifierExpected }); } // Same identifier for enum members [Fact] public void CS0102ERR_DuplicateNameInClass_SameIDForEnum() { var text = @"enum TestEnum { One, One }"; VerifyEnumsValue(text, "TestEnum", 0, 1); var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass }); } // Modifiers for enum [Fact] public void CS0109WRN_NewNotRequired_ModifiersForEnum() { var text = @"class Program { protected enum Figure1 { One = 1 }; // OK new public enum Figure2 { Zero = 0 }; // new + protection modifier is OK abstract enum Figure3 { Zero }; // abstract not valid private private enum Figure4 { One = 1 }; // Duplicate modifier is not OK private public enum Figure5 { }; // More than one protection modifiers is not OK sealed enum Figure0 { Zero }; // sealed not valid new enum Figure { Zero }; // OK }"; //VerifyEnumsValue(text, "TestEnum", 0, 1); var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,19): error CS0106: The modifier 'abstract' is not valid for this item // abstract enum Figure3 { Zero }; // abstract not valid Diagnostic(ErrorCode.ERR_BadMemberFlag, "Figure3").WithArguments("abstract").WithLocation(5, 19), // (6,13): error CS1004: Duplicate 'private' modifier // private private enum Figure4 { One = 1 }; // Duplicate modifier is not OK Diagnostic(ErrorCode.ERR_DuplicateModifier, "private").WithArguments("private").WithLocation(6, 13), // (7,25): error CS0107: More than one protection modifier // private public enum Figure5 { }; // More than one protection modifiers is not OK Diagnostic(ErrorCode.ERR_BadMemberProtection, "Figure5").WithLocation(7, 25), // (8,17): error CS0106: The modifier 'sealed' is not valid for this item // sealed enum Figure0 { Zero }; // sealed not valid Diagnostic(ErrorCode.ERR_BadMemberFlag, "Figure0").WithArguments("sealed").WithLocation(8, 17), // (9,14): warning CS0109: The member 'Program.Figure' does not hide an accessible member. The new keyword is not required. // new enum Figure { Zero }; // OK Diagnostic(ErrorCode.WRN_NewNotRequired, "Figure").WithArguments("Program.Figure").WithLocation(9, 14), // (4,21): warning CS0109: The member 'Program.Figure2' does not hide an accessible member. The new keyword is not required. // new public enum Figure2 { Zero = 0 }; // new + protection modifier is OK Diagnostic(ErrorCode.WRN_NewNotRequired, "Figure2").WithArguments("Program.Figure2").WithLocation(4, 21) ); } [WorkItem(527757, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527757")] // Modifiers for enum member [Fact()] public void CS1041ERR_IdentifierExpectedKW_ModifiersForEnumMember() { var text = @"enum ColorA { public Red } "; //VerifyEnumsValue(text, "ColorA", 0); var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,2): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (3,12): error CS0116: A namespace does not directly contain members such as fields or methods // public Red Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Red"), // (4,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}")); text = @"enum ColorA { void goo() {} } "; VerifyEnumsValue(text, "ColorA", 0); var comp1 = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp1.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_IdentifierExpectedKW }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_SyntaxError }); } // Flag Attribute and Enumerate a Enum [Fact] public void FlagOnEnum() { var text = @" [System.Flags] public enum Suits { ValueA = 1, ValueB = 2, ValueC = 4, ValueD = 8, Combi = ValueA | ValueB } "; VerifyEnumsValue(text, "Suits", 1, 2, 4, 8, 3); } // Customer Attribute on Enum declaration [Fact] public void AttributeOnEnum() { var text = @" class Attr1 : System.Attribute { } [Attr1] enum Figure { One, Two, Three }; "; VerifyEnumsValue(text, "Figure", 0, 1, 2); var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics()); } // Convert integer to Enum instance [ClrOnlyFact(ClrOnlyReason.Unknown)] public void ConvertOnEnum() { var source = @" using System; class c1 { public enum Suits { ValueA = 1, ValueB = 2, ValueC = 4, ValueD = 2, ValueE = 2, } static void Main(string[] args) { Suits S = (Suits)Enum.ToObject(typeof(Suits), 2); Console.WriteLine(S.ToString()); // ValueE Suits S1 = (Suits)Enum.ToObject(typeof(Suits), -1); Console.WriteLine(S1.ToString()); // -1 } } "; VerifyEnumsValue(source, "c1.Suits", 1, 2, 4, 2, 2); CompileAndVerify(source, expectedOutput: @" ValueE -1 "); } // Enum used in switch [Fact] public void CS0152ERR_DuplicateCaseLabel_SwitchInEnum() { var source = @" class c1 { public enum Suits { ValueA, ValueB, ValueC, } public void main() { Suits s = Suits.ValueA; switch (s) { case Suits.ValueA: break; case Suits.ValueB: break; case Suits.ValueC: break; default: break; } } } "; var comp = CreateCompilation(source); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics()); source = @" class c1 { public enum Suits { ValueA = 2, ValueB, ValueC = 2, } public void main() { Suits s = Suits.ValueA; switch (s) { case Suits.ValueA: break; case Suits.ValueB: break; case Suits.ValueC: break; default: break; } } } "; comp = CreateCompilation(source); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateCaseLabel }); } // The literal 0 implicitly converts to any enum type. [ClrOnlyFact] public void ZeroInEnum() { var source = @" using System; class c1 { enum Gender : byte { Male = 2 } static void Main(string[] args) { Gender s = 0; Console.WriteLine(s); s = -0; Console.WriteLine(s); s = 0.0e+999; Console.WriteLine(s); } } "; CompileAndVerify(source, expectedOutput: @" 0 0 0 "); } // Derived. [Fact] public void CS0527ERR_NonInterfaceInInterfaceList_DerivedFromEnum() { var text = @" enum A { Red } struct C : A{} interface D : A{} "; var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList }); } // Enums can Not be declared in nested enum declaration [Fact] public void CS1022ERR_EOFExpected_NestedFromEnum() { var text = @" public enum Num { { public enum Figure { Zero }; } } "; VerifyEnumsValue(text, "Num"); VerifyEnumsValue(text, "Figure", 0); var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_IdentifierExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } // Enums can be declared anywhere [Fact] public void DeclEnum() { var text = @" namespace ns { enum Gender { Male } } struct B { enum Gender { Male } } "; VerifyEnumsValue(text, "ns.Gender", 0); VerifyEnumsValue(text, "B.Gender", 0); } // Enums obey local scope rules [Fact] public void DeclEnum_01() { var text = @" namespace ns { enum E1 { yes = 1, no = yes - 1 }; public class mine { public enum E1 { yes = 1, no = yes - 1 }; } } "; VerifyEnumsValue(text, "ns.E1", 1, 0); VerifyEnumsValue(text, "ns.mine.E1", 1, 0); } // Nullable Enums [Fact] public void NullableOfEnum() { var source = @" enum EnumA { }; enum EnumB : long { Num = 1000 }; class c1 { static public void Main(string[] args) { EnumA a = 0; EnumA? c = null; a = (EnumA)c; } } "; VerifyEnumsValue(source, "EnumB", 1000L); } // Operator on null and enum [Fact] public void OperatorOnNullableAndEnum() { var source = @"class c1 { MyEnum? e = null & MyEnum.One; } enum MyEnum { One }"; var comp = CreateCompilation(source).VerifyDiagnostics( // (3,17): warning CS0458: The result of the expression is always 'null' of type 'MyEnum?' // MyEnum? e = null & MyEnum.One; Diagnostic(ErrorCode.WRN_AlwaysNull, "null & MyEnum.One").WithArguments("MyEnum?") ); } [WorkItem(5030, "DevDiv_Projects/Roslyn")] // Operator on enum [Fact] public void CS0019ERR_BadBinaryOps_OperatorOnEnum() { var source = @" class c1 { static public void Main(string[] args) { Enum1 e1 = e1 + 5L; Enum2 e2 = e1 + e2; e1 = Enum1.A1 + Enum1.B1; bool b1 = e1 == 1; bool b7 = e1 == e2; e1++; // OK --e2; // OK e1 = e1 ^ Enum1.A1; // OK e1 ^= Enum1.B1; // OK var s = sizeof(Enum1); // OK } } public enum Enum1 { A1 = 1, B1 = 2 }; public enum Enum2 : byte { A2, B2 }; "; var comp = CreateCompilation(source).VerifyDiagnostics( // (6,20): error CS0019: Operator '+' cannot be applied to operands of type 'Enum1' and 'long' // Enum1 e1 = e1 + 5L; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 + 5L").WithArguments("+", "Enum1", "long"), // (7,20): error CS0019: Operator '+' cannot be applied to operands of type 'Enum1' and 'Enum2' // Enum2 e2 = e1 + e2; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 + e2").WithArguments("+", "Enum1", "Enum2"), // (8,14): error CS0019: Operator '+' cannot be applied to operands of type 'Enum1' and 'Enum1' // e1 = Enum1.A1 + Enum1.B1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "Enum1.A1 + Enum1.B1").WithArguments("+", "Enum1", "Enum1"), // (9,19): error CS0019: Operator '==' cannot be applied to operands of type 'Enum1' and 'int' // bool b1 = e1 == 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 == 1").WithArguments("==", "Enum1", "int"), // (10,19): error CS0019: Operator '==' cannot be applied to operands of type 'Enum1' and 'Enum2' // bool b7 = e1 == e2; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 == e2").WithArguments("==", "Enum1", "Enum2"), // (6,20): error CS0165: Use of unassigned local variable 'e1' // Enum1 e1 = e1 + 5L; Diagnostic(ErrorCode.ERR_UseDefViolation, "e1").WithArguments("e1"), // (7,25): error CS0165: Use of unassigned local variable 'e2' // Enum2 e2 = e1 + e2; Diagnostic(ErrorCode.ERR_UseDefViolation, "e2").WithArguments("e2"), // (15,13): warning CS0219: The variable 's' is assigned but its value is never used // var s = sizeof(Enum1); // OK Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s")); } [WorkItem(5030, "DevDiv_Projects/Roslyn")] // Operator on enum member [ClrOnlyFact] public void OperatorOnEnumMember() { var source = @" using System; class c1 { static public void Main(string[] args) { E s = E.one; var b1 = E.three > E.two; var b2 = E.three < E.two; var b3 = E.three == E.two; var b4 = E.three != E.two; var b5 = s > E.two; var b6 = s < E.two; var b7 = s == E.two; var b8 = s != E.two; Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3); Console.WriteLine(b4); Console.WriteLine(b5); Console.WriteLine(b6); Console.WriteLine(b7); Console.WriteLine(b8); } } public enum E { one = 1, two = 2, three = 3 }; "; CompileAndVerify(source, expectedOutput: @" True False False True False True False True "); } // CLS-Compliant [Fact] public void CS3009WRN_CLS_BadBase_CLSCompliantOnEnum() { var text = @" [assembly: System.CLSCompliant(true)] public class c1 { public enum COLORS : uint { RED, GREEN, BLUE }; } "; var comp = CreateCompilation(text); VerifyEnumsValue(comp, "c1.COLORS", SpecialType.System_UInt32, 0u, 1u, 2u); comp.VerifyDiagnostics( // (5,17): warning CS3009: 'c1.COLORS': base type 'uint' is not CLS-compliant // public enum COLORS : uint { RED, GREEN, BLUE }; Diagnostic(ErrorCode.WRN_CLS_BadBase, "COLORS").WithArguments("c1.COLORS", "uint")); } [WorkItem(539178, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539178")] // No underlying type after ':' [Fact] public void CS3031ERR_TypeExpected_NoUnderlyingTypeForEnum() { var text = @"enum Figure : { One, Two, Three } "; var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_TypeExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntegralTypeExpected }); VerifyEnumsValue(comp, "Figure", SpecialType.System_Int32, 0, 1, 2); } [Fact] public void CS1008ERR_IntegralTypeExpected() { var text = @"enum Figure : System.Int16 { One, Two, Three } "; var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics()); // ok VerifyEnumsValue(comp, "Figure", SpecialType.System_Int16, (short)0, (short)1, (short)2); text = @"class C { } enum Figure : C { One, Two, Three } "; comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_IntegralTypeExpected }); VerifyEnumsValue(comp, "Figure", SpecialType.System_Int32, 0, 1, 2); } // 'partial' as Enum name [Fact] public void partialAsEnumName() { var text = @" partial class EnumPartial { internal enum partial { } partial M; } "; VerifyEnumsValue(text, "EnumPartial.partial"); var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,13): warning CS0169: The field 'EnumPartial.M' is never used // partial M; Diagnostic(ErrorCode.WRN_UnreferencedField, "M").WithArguments("EnumPartial.M") ); var classEnum = comp.SourceModule.GlobalNamespace.GetMembers("EnumPartial").Single() as NamedTypeSymbol; var member = classEnum.GetMembers("M").Single() as FieldSymbol; Assert.Equal(TypeKind.Enum, member.Type.TypeKind); } // Enum as an optional parameter [Fact] public void CS1763ERR_NotNullRefDefaultParameter_EnumAsOptionalParameter() { var text = @" enum ABC { a, b, c } class c1 { public int Goo(ABC o = ABC.a | ABC.b) { return 0; } public int Moo(object o = ABC.a) { return 1; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (9,27): error CS1763: 'o' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null // public int Moo(object o = ABC.a) Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "o").WithArguments("o", "object")); } [WorkItem(540765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540765")] [Fact] public void TestInitializeWithEnumMemberEnumConst() { var text = @" class Test { public enum E0 : short { Member1 } const E0 e0 = E0.Member1; public enum E1 { Member1, Member2 = e1, Member3 = e0 } const E1 e1 = E1.Member1; }"; CreateCompilation(text).VerifyDiagnostics(); // No Errors } [WorkItem(540765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540765")] [Fact] public void TestInitializeWithEnumMemberEnumConst2() { var text = @" class Test { const E1 e = E1.Member1; public enum E1 { Member2 = e, Member1 } }"; CreateCompilation(text).VerifyDiagnostics( // (4,14): error CS0110: The evaluation of the constant value for 'Test.e' involves a circular definition Diagnostic(ErrorCode.ERR_CircConstValue, "e").WithArguments("Test.e")); // No Errors } [WorkItem(540765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540765")] [Fact] public void TestInitializeWithEnumMemberEnumConst3() { var text = @" class Test { const E1 e = E1.Member1; public enum E1 { Member1, Member2 = e //fine } public enum E2 { Member = e //fine } public enum E3 { Member = (E3)e //CS0266 } public enum E4 { Member = (e) //fine } public enum E5 { Member = (e) + 1 //fine } }"; CreateCompilation(text).VerifyDiagnostics( // (16,18): error CS0266: Cannot implicitly convert type 'Test.E3' to 'int'. An explicit conversion exists (are you missing a cast?) // Member = (E3)e Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "(E3)e").WithArguments("Test.E3", "int")); } [WorkItem(540771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540771")] [Fact] public void TestUseEnumMemberFromBaseGenericType() { var text = @" class Base<T, U> { public enum Enum1 { A, B, C } } class Derived<T, U> : Base<U, T> { const Enum1 E = Enum1.C; }"; CreateCompilation(text).VerifyDiagnostics(); // No Errors } [WorkItem(667303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667303")] [Fact] public void TestFullNameForEnumBaseType() { var text = @"public enum Works1 : byte {} public enum Works2 : sbyte {} public enum Works3 : short {} public enum Works4 : ushort {} public enum Works5 : int {} public enum Works6 : uint {} public enum Works7 : long {} public enum Works8 : ulong {} public enum Breaks1 : System.Byte {} public enum Breaks2 : System.SByte {} public enum Breaks3 : System.Int16 {} public enum Breaks4 : System.UInt16 {} public enum Breaks5 : System.Int32 {} public enum Breaks6 : System.UInt32 {} public enum Breaks7 : System.Int64 {} public enum Breaks8 : System.UInt64 {}"; CreateCompilation(text).VerifyDiagnostics(); // No Errors } [WorkItem(667303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667303")] [Fact] public void TestBadEnumBaseType() { var text = @"public enum Breaks1 : string {} public enum Breaks2 : System.String {}"; CreateCompilation(text).VerifyDiagnostics( // (1,23): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // public enum Breaks1 : string {} Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "string").WithLocation(1, 23), // (2,23): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // public enum Breaks2 : System.String {} Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "System.String").WithLocation(2, 23) ); } [WorkItem(750553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750553")] [Fact] public void InvalidEnumUnderlyingType() { var text = @"enum E1 : int[] { } enum E2 : int* { } enum E3 : dynamic { } class C<T> { enum E4 : T { } } "; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); compilation.VerifyDiagnostics( // (2,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // enum E2 : int* { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*").WithLocation(2, 11), // (2,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E2 : int* { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int*").WithLocation(2, 11), // (3,11): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference? // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_DynamicAttributeMissing, "dynamic").WithArguments("System.Runtime.CompilerServices.DynamicAttribute").WithLocation(3, 11), // (3,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "dynamic").WithLocation(3, 11), // (1,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E1 : int[] { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int[]").WithLocation(1, 11), // (4,24): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // class C<T> { enum E4 : T { } } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "T").WithLocation(4, 24) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var diagnostics = model.GetDeclarationDiagnostics(); diagnostics.Verify( // (2,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // enum E2 : int* { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*").WithLocation(2, 11), // (2,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E2 : int* { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int*").WithLocation(2, 11), // (1,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E1 : int[] { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int[]").WithLocation(1, 11), // (3,11): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference? // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_DynamicAttributeMissing, "dynamic").WithArguments("System.Runtime.CompilerServices.DynamicAttribute").WithLocation(3, 11), // (3,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "dynamic").WithLocation(3, 11), // (4,24): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // class C<T> { enum E4 : T { } } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "T").WithLocation(4, 24) ); var decls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<EnumDeclarationSyntax>().ToArray(); Assert.Equal(4, decls.Length); foreach (var decl in decls) { var symbol = model.GetDeclaredSymbol(decl); var type = symbol.EnumUnderlyingType; Assert.Equal(SpecialType.System_Int32, type.SpecialType); } } private List<Symbol> VerifyEnumsValue(string text, string enumName, params object[] expectedEnumValues) { var comp = CreateCompilation(text); var specialType = SpecialType.System_Int32; if (expectedEnumValues.Length > 0) { var first = expectedEnumValues.First(); if (first != null && first.GetType() == typeof(long)) specialType = SpecialType.System_Int64; } return VerifyEnumsValue(comp, enumName, specialType, expectedEnumValues); } private List<Symbol> VerifyEnumsValue(CSharpCompilation comp, string enumName, SpecialType underlyingType, params object[] expectedEnumValues) { var global = comp.SourceModule.GlobalNamespace; var symEnum = GetSymbolByFullName(comp, enumName) as NamedTypeSymbol; Assert.NotNull(symEnum); var type = symEnum.EnumUnderlyingType; Assert.NotNull(type); Assert.Equal(underlyingType, type.SpecialType); var fields = symEnum.GetMembers().OfType<FieldSymbol>().Cast<Symbol>().ToList(); Assert.Equal(expectedEnumValues.Length, fields.Count); var count = 0; foreach (var item in fields) { var field = item as FieldSymbol; Assert.Equal(expectedEnumValues[count++], field.ConstantValue); } return fields; } private static Symbol GetSymbolByFullName(CSharpCompilation compilation, string memberName) { string[] names = memberName.Split('.'); Symbol currentSymbol = compilation.GlobalNamespace; foreach (var name in names) { Assert.True(currentSymbol is NamespaceOrTypeSymbol, string.Format("{0} does not have members", currentSymbol.ToTestDisplayString())); var currentContainer = (NamespaceOrTypeSymbol)currentSymbol; var members = currentContainer.GetMembers(name); Assert.True(members.Length > 0, string.Format("No members named {0} inside {1}", name, currentSymbol.ToTestDisplayString())); Assert.True(members.Length <= 1, string.Format("Multiple members named {0} inside {1}", name, currentSymbol.ToTestDisplayString())); currentSymbol = members.First(); } return currentSymbol; } } }
// 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.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.Source { public class EnumTests : CSharpTestBase { // The value of first enumerator, and the value of each successive enumerator [Fact] public void ValueOfFirst() { var text = @"enum Suits { ValueA, ValueB, ValueC, ValueD } "; VerifyEnumsValue(text, "Suits", 0, 1, 2, 3); } // The value can be explicated initialized [Fact] public void ExplicateInit() { var text = @"public enum Suits { ValueA = -1, ValueB = 2, ValueC = 3, ValueD = 4, }; "; VerifyEnumsValue(text, "Suits", -1, 2, 3, 4); } // The value can be explicated and implicit initialized [Fact] public void MixedInit() { var text = @"public enum Suits { ValueA, ValueB = 10, ValueC, ValueD, }; "; VerifyEnumsValue(text, "Suits", 0, 10, 11, 12); } // Enumerator initializers must be of integral or enumeration type [Fact] public void OutOfUnderlyingRange() { var text = @"public enum Suits : byte { ValueA = ""3"", // Can't implicitly convert ValueB = 2.2, // Can't implicitly convert ValueC = 257 // Out of underlying range }; "; var comp = CreateCompilation(text); VerifyEnumsValue(comp, "Suits", SpecialType.System_Byte, null, (byte)2, null); comp.VerifyDiagnostics( // (3,10): error CS0029: Cannot implicitly convert type 'string' to 'byte' // ValueA = "3", // Can't implicitly convert Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""3""").WithArguments("string", "byte").WithLocation(3, 10), // (4,10): error CS0266: Cannot implicitly convert type 'double' to 'byte'. An explicit conversion exists (are you missing a cast?) // ValueB = 2.2, // Can't implicitly convert Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "2.2").WithArguments("double", "byte").WithLocation(4, 10), // (5,10): error CS0031: Constant value '257' cannot be converted to a 'byte' // ValueC = 257 // Out of underlying range Diagnostic(ErrorCode.ERR_ConstOutOfRange, "257").WithArguments("257", "byte").WithLocation(5, 10) ); text = @"enum Suits : short { a, b, c, d = -65536, e, f }"; comp = CreateCompilation(text); VerifyEnumsValue(comp, "Suits", SpecialType.System_Int16, (short)0, (short)1, (short)2, null, null, null); comp.VerifyDiagnostics( // (1,35): error CS0031: Constant value '-65536' cannot be converted to a 'short' // enum Suits : short { a, b, c, d = -65536, e, f } Diagnostic(ErrorCode.ERR_ConstOutOfRange, "-65536").WithArguments("-65536", "short").WithLocation(1, 35) ); } // Explicit associated value [Fact] public void ExplicitAssociated() { var text = @"class C<T> { const int field = 100; enum TestEnum { A, B = A, // another member C = D, // another member D = (byte)11, // type can be implicitly converted to underlying type E = 'a', // type can be implicitly converted to underlying type F = 3 + 5, // expression G = field, // const field TestEnum, // its own type name var, // contextual keyword T, // Type parameter }; enum EnumB { B = TestEnum.T }; } "; VerifyEnumsValue(text, "C.TestEnum", 0, 0, 11, 11, 97, 8, 100, 101, 102, 103); VerifyEnumsValue(text, "C.EnumB", 103); text = @"class c1 { public static int StaticField = 10; public static readonly int ReadonlyField = 100; enum EnumTest { A = StaticField, B = ReadonlyField }; } "; VerifyEnumsValue(text, "c1.EnumTest", null, null); } [WorkItem(539167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539167")] // No enum-body [Fact] public void CS1514ERR_LbraceExpected_NoEnumBody() { var text = @"enum Figure ;"; VerifyEnumsValue(text, "Figure"); var comp = CreateCompilation(text); // Same errors as parsing "class Name ;". DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_LbraceExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } [Fact] public void EnumEOFBeforeMembers() { var text = @"enum E"; VerifyEnumsValue(text, "E"); var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_LbraceExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } [Fact] public void EnumEOFWithinMembers() { var text = @"enum E {"; VerifyEnumsValue(text, "E"); var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } // No enum-body [Fact] public void NullEnumBody() { var text = @"enum Figure { }"; VerifyEnumsValue(text, "Figure"); } // No identifier [Fact] public void CS1001ERR_IdentifierExpected_NoIDForEnum() { var text = @"enum { One, Two, Three };"; var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_IdentifierExpected }); } // Same identifier for enum members [Fact] public void CS0102ERR_DuplicateNameInClass_SameIDForEnum() { var text = @"enum TestEnum { One, One }"; VerifyEnumsValue(text, "TestEnum", 0, 1); var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass }); } // Modifiers for enum [Fact] public void CS0109WRN_NewNotRequired_ModifiersForEnum() { var text = @"class Program { protected enum Figure1 { One = 1 }; // OK new public enum Figure2 { Zero = 0 }; // new + protection modifier is OK abstract enum Figure3 { Zero }; // abstract not valid private private enum Figure4 { One = 1 }; // Duplicate modifier is not OK private public enum Figure5 { }; // More than one protection modifiers is not OK sealed enum Figure0 { Zero }; // sealed not valid new enum Figure { Zero }; // OK }"; //VerifyEnumsValue(text, "TestEnum", 0, 1); var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,19): error CS0106: The modifier 'abstract' is not valid for this item // abstract enum Figure3 { Zero }; // abstract not valid Diagnostic(ErrorCode.ERR_BadMemberFlag, "Figure3").WithArguments("abstract").WithLocation(5, 19), // (6,13): error CS1004: Duplicate 'private' modifier // private private enum Figure4 { One = 1 }; // Duplicate modifier is not OK Diagnostic(ErrorCode.ERR_DuplicateModifier, "private").WithArguments("private").WithLocation(6, 13), // (7,25): error CS0107: More than one protection modifier // private public enum Figure5 { }; // More than one protection modifiers is not OK Diagnostic(ErrorCode.ERR_BadMemberProtection, "Figure5").WithLocation(7, 25), // (8,17): error CS0106: The modifier 'sealed' is not valid for this item // sealed enum Figure0 { Zero }; // sealed not valid Diagnostic(ErrorCode.ERR_BadMemberFlag, "Figure0").WithArguments("sealed").WithLocation(8, 17), // (9,14): warning CS0109: The member 'Program.Figure' does not hide an accessible member. The new keyword is not required. // new enum Figure { Zero }; // OK Diagnostic(ErrorCode.WRN_NewNotRequired, "Figure").WithArguments("Program.Figure").WithLocation(9, 14), // (4,21): warning CS0109: The member 'Program.Figure2' does not hide an accessible member. The new keyword is not required. // new public enum Figure2 { Zero = 0 }; // new + protection modifier is OK Diagnostic(ErrorCode.WRN_NewNotRequired, "Figure2").WithArguments("Program.Figure2").WithLocation(4, 21) ); } [WorkItem(527757, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527757")] // Modifiers for enum member [Fact()] public void CS1041ERR_IdentifierExpectedKW_ModifiersForEnumMember() { var text = @"enum ColorA { public Red } "; //VerifyEnumsValue(text, "ColorA", 0); var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,2): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (3,12): error CS0116: A namespace does not directly contain members such as fields or methods // public Red Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Red"), // (4,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}")); text = @"enum ColorA { void goo() {} } "; VerifyEnumsValue(text, "ColorA", 0); var comp1 = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp1.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_IdentifierExpectedKW }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_SyntaxError }); } // Flag Attribute and Enumerate a Enum [Fact] public void FlagOnEnum() { var text = @" [System.Flags] public enum Suits { ValueA = 1, ValueB = 2, ValueC = 4, ValueD = 8, Combi = ValueA | ValueB } "; VerifyEnumsValue(text, "Suits", 1, 2, 4, 8, 3); } // Customer Attribute on Enum declaration [Fact] public void AttributeOnEnum() { var text = @" class Attr1 : System.Attribute { } [Attr1] enum Figure { One, Two, Three }; "; VerifyEnumsValue(text, "Figure", 0, 1, 2); var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics()); } // Convert integer to Enum instance [ClrOnlyFact(ClrOnlyReason.Unknown)] public void ConvertOnEnum() { var source = @" using System; class c1 { public enum Suits { ValueA = 1, ValueB = 2, ValueC = 4, ValueD = 2, ValueE = 2, } static void Main(string[] args) { Suits S = (Suits)Enum.ToObject(typeof(Suits), 2); Console.WriteLine(S.ToString()); // ValueE Suits S1 = (Suits)Enum.ToObject(typeof(Suits), -1); Console.WriteLine(S1.ToString()); // -1 } } "; VerifyEnumsValue(source, "c1.Suits", 1, 2, 4, 2, 2); CompileAndVerify(source, expectedOutput: @" ValueE -1 "); } // Enum used in switch [Fact] public void CS0152ERR_DuplicateCaseLabel_SwitchInEnum() { var source = @" class c1 { public enum Suits { ValueA, ValueB, ValueC, } public void main() { Suits s = Suits.ValueA; switch (s) { case Suits.ValueA: break; case Suits.ValueB: break; case Suits.ValueC: break; default: break; } } } "; var comp = CreateCompilation(source); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics()); source = @" class c1 { public enum Suits { ValueA = 2, ValueB, ValueC = 2, } public void main() { Suits s = Suits.ValueA; switch (s) { case Suits.ValueA: break; case Suits.ValueB: break; case Suits.ValueC: break; default: break; } } } "; comp = CreateCompilation(source); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateCaseLabel }); } // The literal 0 implicitly converts to any enum type. [ClrOnlyFact] public void ZeroInEnum() { var source = @" using System; class c1 { enum Gender : byte { Male = 2 } static void Main(string[] args) { Gender s = 0; Console.WriteLine(s); s = -0; Console.WriteLine(s); s = 0.0e+999; Console.WriteLine(s); } } "; CompileAndVerify(source, expectedOutput: @" 0 0 0 "); } // Derived. [Fact] public void CS0527ERR_NonInterfaceInInterfaceList_DerivedFromEnum() { var text = @" enum A { Red } struct C : A{} interface D : A{} "; var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList }); } // Enums can Not be declared in nested enum declaration [Fact] public void CS1022ERR_EOFExpected_NestedFromEnum() { var text = @" public enum Num { { public enum Figure { Zero }; } } "; VerifyEnumsValue(text, "Num"); VerifyEnumsValue(text, "Figure", 0); var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodesNoLineColumn(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_EOFExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_IdentifierExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_RbraceExpected }); } // Enums can be declared anywhere [Fact] public void DeclEnum() { var text = @" namespace ns { enum Gender { Male } } struct B { enum Gender { Male } } "; VerifyEnumsValue(text, "ns.Gender", 0); VerifyEnumsValue(text, "B.Gender", 0); } // Enums obey local scope rules [Fact] public void DeclEnum_01() { var text = @" namespace ns { enum E1 { yes = 1, no = yes - 1 }; public class mine { public enum E1 { yes = 1, no = yes - 1 }; } } "; VerifyEnumsValue(text, "ns.E1", 1, 0); VerifyEnumsValue(text, "ns.mine.E1", 1, 0); } // Nullable Enums [Fact] public void NullableOfEnum() { var source = @" enum EnumA { }; enum EnumB : long { Num = 1000 }; class c1 { static public void Main(string[] args) { EnumA a = 0; EnumA? c = null; a = (EnumA)c; } } "; VerifyEnumsValue(source, "EnumB", 1000L); } // Operator on null and enum [Fact] public void OperatorOnNullableAndEnum() { var source = @"class c1 { MyEnum? e = null & MyEnum.One; } enum MyEnum { One }"; var comp = CreateCompilation(source).VerifyDiagnostics( // (3,17): warning CS0458: The result of the expression is always 'null' of type 'MyEnum?' // MyEnum? e = null & MyEnum.One; Diagnostic(ErrorCode.WRN_AlwaysNull, "null & MyEnum.One").WithArguments("MyEnum?") ); } [WorkItem(5030, "DevDiv_Projects/Roslyn")] // Operator on enum [Fact] public void CS0019ERR_BadBinaryOps_OperatorOnEnum() { var source = @" class c1 { static public void Main(string[] args) { Enum1 e1 = e1 + 5L; Enum2 e2 = e1 + e2; e1 = Enum1.A1 + Enum1.B1; bool b1 = e1 == 1; bool b7 = e1 == e2; e1++; // OK --e2; // OK e1 = e1 ^ Enum1.A1; // OK e1 ^= Enum1.B1; // OK var s = sizeof(Enum1); // OK } } public enum Enum1 { A1 = 1, B1 = 2 }; public enum Enum2 : byte { A2, B2 }; "; var comp = CreateCompilation(source).VerifyDiagnostics( // (6,20): error CS0019: Operator '+' cannot be applied to operands of type 'Enum1' and 'long' // Enum1 e1 = e1 + 5L; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 + 5L").WithArguments("+", "Enum1", "long"), // (7,20): error CS0019: Operator '+' cannot be applied to operands of type 'Enum1' and 'Enum2' // Enum2 e2 = e1 + e2; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 + e2").WithArguments("+", "Enum1", "Enum2"), // (8,14): error CS0019: Operator '+' cannot be applied to operands of type 'Enum1' and 'Enum1' // e1 = Enum1.A1 + Enum1.B1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "Enum1.A1 + Enum1.B1").WithArguments("+", "Enum1", "Enum1"), // (9,19): error CS0019: Operator '==' cannot be applied to operands of type 'Enum1' and 'int' // bool b1 = e1 == 1; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 == 1").WithArguments("==", "Enum1", "int"), // (10,19): error CS0019: Operator '==' cannot be applied to operands of type 'Enum1' and 'Enum2' // bool b7 = e1 == e2; Diagnostic(ErrorCode.ERR_BadBinaryOps, "e1 == e2").WithArguments("==", "Enum1", "Enum2"), // (6,20): error CS0165: Use of unassigned local variable 'e1' // Enum1 e1 = e1 + 5L; Diagnostic(ErrorCode.ERR_UseDefViolation, "e1").WithArguments("e1"), // (7,25): error CS0165: Use of unassigned local variable 'e2' // Enum2 e2 = e1 + e2; Diagnostic(ErrorCode.ERR_UseDefViolation, "e2").WithArguments("e2"), // (15,13): warning CS0219: The variable 's' is assigned but its value is never used // var s = sizeof(Enum1); // OK Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s")); } [WorkItem(5030, "DevDiv_Projects/Roslyn")] // Operator on enum member [ClrOnlyFact] public void OperatorOnEnumMember() { var source = @" using System; class c1 { static public void Main(string[] args) { E s = E.one; var b1 = E.three > E.two; var b2 = E.three < E.two; var b3 = E.three == E.two; var b4 = E.three != E.two; var b5 = s > E.two; var b6 = s < E.two; var b7 = s == E.two; var b8 = s != E.two; Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3); Console.WriteLine(b4); Console.WriteLine(b5); Console.WriteLine(b6); Console.WriteLine(b7); Console.WriteLine(b8); } } public enum E { one = 1, two = 2, three = 3 }; "; CompileAndVerify(source, expectedOutput: @" True False False True False True False True "); } // CLS-Compliant [Fact] public void CS3009WRN_CLS_BadBase_CLSCompliantOnEnum() { var text = @" [assembly: System.CLSCompliant(true)] public class c1 { public enum COLORS : uint { RED, GREEN, BLUE }; } "; var comp = CreateCompilation(text); VerifyEnumsValue(comp, "c1.COLORS", SpecialType.System_UInt32, 0u, 1u, 2u); comp.VerifyDiagnostics( // (5,17): warning CS3009: 'c1.COLORS': base type 'uint' is not CLS-compliant // public enum COLORS : uint { RED, GREEN, BLUE }; Diagnostic(ErrorCode.WRN_CLS_BadBase, "COLORS").WithArguments("c1.COLORS", "uint")); } [WorkItem(539178, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539178")] // No underlying type after ':' [Fact] public void CS3031ERR_TypeExpected_NoUnderlyingTypeForEnum() { var text = @"enum Figure : { One, Two, Three } "; var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_TypeExpected }, new ErrorDescription { Code = (int)ErrorCode.ERR_IntegralTypeExpected }); VerifyEnumsValue(comp, "Figure", SpecialType.System_Int32, 0, 1, 2); } [Fact] public void CS1008ERR_IntegralTypeExpected() { var text = @"enum Figure : System.Int16 { One, Two, Three } "; var comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics()); // ok VerifyEnumsValue(comp, "Figure", SpecialType.System_Int16, (short)0, (short)1, (short)2); text = @"class C { } enum Figure : C { One, Two, Three } "; comp = CreateCompilation(text); DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics(), new ErrorDescription { Code = (int)ErrorCode.ERR_IntegralTypeExpected }); VerifyEnumsValue(comp, "Figure", SpecialType.System_Int32, 0, 1, 2); } // 'partial' as Enum name [Fact] public void partialAsEnumName() { var text = @" partial class EnumPartial { internal enum partial { } partial M; } "; VerifyEnumsValue(text, "EnumPartial.partial"); var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,13): warning CS0169: The field 'EnumPartial.M' is never used // partial M; Diagnostic(ErrorCode.WRN_UnreferencedField, "M").WithArguments("EnumPartial.M") ); var classEnum = comp.SourceModule.GlobalNamespace.GetMembers("EnumPartial").Single() as NamedTypeSymbol; var member = classEnum.GetMembers("M").Single() as FieldSymbol; Assert.Equal(TypeKind.Enum, member.Type.TypeKind); } // Enum as an optional parameter [Fact] public void CS1763ERR_NotNullRefDefaultParameter_EnumAsOptionalParameter() { var text = @" enum ABC { a, b, c } class c1 { public int Goo(ABC o = ABC.a | ABC.b) { return 0; } public int Moo(object o = ABC.a) { return 1; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (9,27): error CS1763: 'o' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null // public int Moo(object o = ABC.a) Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "o").WithArguments("o", "object")); } [WorkItem(540765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540765")] [Fact] public void TestInitializeWithEnumMemberEnumConst() { var text = @" class Test { public enum E0 : short { Member1 } const E0 e0 = E0.Member1; public enum E1 { Member1, Member2 = e1, Member3 = e0 } const E1 e1 = E1.Member1; }"; CreateCompilation(text).VerifyDiagnostics(); // No Errors } [WorkItem(540765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540765")] [Fact] public void TestInitializeWithEnumMemberEnumConst2() { var text = @" class Test { const E1 e = E1.Member1; public enum E1 { Member2 = e, Member1 } }"; CreateCompilation(text).VerifyDiagnostics( // (4,14): error CS0110: The evaluation of the constant value for 'Test.e' involves a circular definition Diagnostic(ErrorCode.ERR_CircConstValue, "e").WithArguments("Test.e")); // No Errors } [WorkItem(540765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540765")] [Fact] public void TestInitializeWithEnumMemberEnumConst3() { var text = @" class Test { const E1 e = E1.Member1; public enum E1 { Member1, Member2 = e //fine } public enum E2 { Member = e //fine } public enum E3 { Member = (E3)e //CS0266 } public enum E4 { Member = (e) //fine } public enum E5 { Member = (e) + 1 //fine } }"; CreateCompilation(text).VerifyDiagnostics( // (16,18): error CS0266: Cannot implicitly convert type 'Test.E3' to 'int'. An explicit conversion exists (are you missing a cast?) // Member = (E3)e Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "(E3)e").WithArguments("Test.E3", "int")); } [WorkItem(540771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540771")] [Fact] public void TestUseEnumMemberFromBaseGenericType() { var text = @" class Base<T, U> { public enum Enum1 { A, B, C } } class Derived<T, U> : Base<U, T> { const Enum1 E = Enum1.C; }"; CreateCompilation(text).VerifyDiagnostics(); // No Errors } [WorkItem(667303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667303")] [Fact] public void TestFullNameForEnumBaseType() { var text = @"public enum Works1 : byte {} public enum Works2 : sbyte {} public enum Works3 : short {} public enum Works4 : ushort {} public enum Works5 : int {} public enum Works6 : uint {} public enum Works7 : long {} public enum Works8 : ulong {} public enum Breaks1 : System.Byte {} public enum Breaks2 : System.SByte {} public enum Breaks3 : System.Int16 {} public enum Breaks4 : System.UInt16 {} public enum Breaks5 : System.Int32 {} public enum Breaks6 : System.UInt32 {} public enum Breaks7 : System.Int64 {} public enum Breaks8 : System.UInt64 {}"; CreateCompilation(text).VerifyDiagnostics(); // No Errors } [WorkItem(667303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667303")] [Fact] public void TestBadEnumBaseType() { var text = @"public enum Breaks1 : string {} public enum Breaks2 : System.String {}"; CreateCompilation(text).VerifyDiagnostics( // (1,23): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // public enum Breaks1 : string {} Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "string").WithLocation(1, 23), // (2,23): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // public enum Breaks2 : System.String {} Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "System.String").WithLocation(2, 23) ); } [WorkItem(750553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750553")] [Fact] public void InvalidEnumUnderlyingType() { var text = @"enum E1 : int[] { } enum E2 : int* { } enum E3 : dynamic { } class C<T> { enum E4 : T { } } "; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); compilation.VerifyDiagnostics( // (2,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // enum E2 : int* { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*").WithLocation(2, 11), // (2,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E2 : int* { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int*").WithLocation(2, 11), // (3,11): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference? // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_DynamicAttributeMissing, "dynamic").WithArguments("System.Runtime.CompilerServices.DynamicAttribute").WithLocation(3, 11), // (3,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "dynamic").WithLocation(3, 11), // (1,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E1 : int[] { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int[]").WithLocation(1, 11), // (4,24): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // class C<T> { enum E4 : T { } } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "T").WithLocation(4, 24) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var diagnostics = model.GetDeclarationDiagnostics(); diagnostics.Verify( // (2,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // enum E2 : int* { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*").WithLocation(2, 11), // (2,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E2 : int* { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int*").WithLocation(2, 11), // (1,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E1 : int[] { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "int[]").WithLocation(1, 11), // (3,11): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference? // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_DynamicAttributeMissing, "dynamic").WithArguments("System.Runtime.CompilerServices.DynamicAttribute").WithLocation(3, 11), // (3,11): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // enum E3 : dynamic { } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "dynamic").WithLocation(3, 11), // (4,24): error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected // class C<T> { enum E4 : T { } } Diagnostic(ErrorCode.ERR_IntegralTypeExpected, "T").WithLocation(4, 24) ); var decls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<EnumDeclarationSyntax>().ToArray(); Assert.Equal(4, decls.Length); foreach (var decl in decls) { var symbol = model.GetDeclaredSymbol(decl); var type = symbol.EnumUnderlyingType; Assert.Equal(SpecialType.System_Int32, type.SpecialType); } } private List<Symbol> VerifyEnumsValue(string text, string enumName, params object[] expectedEnumValues) { var comp = CreateCompilation(text); var specialType = SpecialType.System_Int32; if (expectedEnumValues.Length > 0) { var first = expectedEnumValues.First(); if (first != null && first.GetType() == typeof(long)) specialType = SpecialType.System_Int64; } return VerifyEnumsValue(comp, enumName, specialType, expectedEnumValues); } private List<Symbol> VerifyEnumsValue(CSharpCompilation comp, string enumName, SpecialType underlyingType, params object[] expectedEnumValues) { var global = comp.SourceModule.GlobalNamespace; var symEnum = GetSymbolByFullName(comp, enumName) as NamedTypeSymbol; Assert.NotNull(symEnum); var type = symEnum.EnumUnderlyingType; Assert.NotNull(type); Assert.Equal(underlyingType, type.SpecialType); var fields = symEnum.GetMembers().OfType<FieldSymbol>().Cast<Symbol>().ToList(); Assert.Equal(expectedEnumValues.Length, fields.Count); var count = 0; foreach (var item in fields) { var field = item as FieldSymbol; Assert.Equal(expectedEnumValues[count++], field.ConstantValue); } return fields; } private static Symbol GetSymbolByFullName(CSharpCompilation compilation, string memberName) { string[] names = memberName.Split('.'); Symbol currentSymbol = compilation.GlobalNamespace; foreach (var name in names) { Assert.True(currentSymbol is NamespaceOrTypeSymbol, string.Format("{0} does not have members", currentSymbol.ToTestDisplayString())); var currentContainer = (NamespaceOrTypeSymbol)currentSymbol; var members = currentContainer.GetMembers(name); Assert.True(members.Length > 0, string.Format("No members named {0} inside {1}", name, currentSymbol.ToTestDisplayString())); Assert.True(members.Length <= 1, string.Format("Multiple members named {0} inside {1}", name, currentSymbol.ToTestDisplayString())); currentSymbol = members.First(); } return currentSymbol; } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Workspaces/Core/Portable/Workspace/Host/Documentation/DocumentationProviderServiceFactory.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.Concurrent; using System.Composition; using System.IO; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceServiceFactory(typeof(IDocumentationProviderService), ServiceLayer.Default), Shared] internal sealed class DocumentationProviderServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentationProviderServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new DocumentationProviderService(); internal sealed class DocumentationProviderService : IDocumentationProviderService { private readonly ConcurrentDictionary<string, DocumentationProvider> _assemblyPathToDocumentationProviderMap = new(); public DocumentationProvider GetDocumentationProvider(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException(nameof(assemblyPath)); } assemblyPath = Path.ChangeExtension(assemblyPath, "xml"); if (!_assemblyPathToDocumentationProviderMap.TryGetValue(assemblyPath, out var provider)) { provider = _assemblyPathToDocumentationProviderMap.GetOrAdd(assemblyPath, _path => XmlDocumentationProvider.CreateFromFile(_path)); } return provider; } } } }
// 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.Concurrent; using System.Composition; using System.IO; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceServiceFactory(typeof(IDocumentationProviderService), ServiceLayer.Default), Shared] internal sealed class DocumentationProviderServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentationProviderServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new DocumentationProviderService(); internal sealed class DocumentationProviderService : IDocumentationProviderService { private readonly ConcurrentDictionary<string, DocumentationProvider> _assemblyPathToDocumentationProviderMap = new(); public DocumentationProvider GetDocumentationProvider(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException(nameof(assemblyPath)); } assemblyPath = Path.ChangeExtension(assemblyPath, "xml"); if (!_assemblyPathToDocumentationProviderMap.TryGetValue(assemblyPath, out var provider)) { provider = _assemblyPathToDocumentationProviderMap.GetOrAdd(assemblyPath, _path => XmlDocumentationProvider.CreateFromFile(_path)); } return provider; } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Workspaces/Core/Portable/Workspace/Host/Status/WorkspaceStatusService.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.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceService(typeof(IWorkspaceStatusService), ServiceLayer.Default), Shared] internal sealed class WorkspaceStatusService : IWorkspaceStatusService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WorkspaceStatusService() { } event EventHandler IWorkspaceStatusService.StatusChanged { add { } remove { } } public Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken) { // by the default, we are always fully loaded return Task.CompletedTask; } public Task<bool> IsFullyLoadedAsync(CancellationToken cancellationToken) { // by the default, we are always fully loaded return SpecializedTasks.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; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceService(typeof(IWorkspaceStatusService), ServiceLayer.Default), Shared] internal sealed class WorkspaceStatusService : IWorkspaceStatusService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public WorkspaceStatusService() { } event EventHandler IWorkspaceStatusService.StatusChanged { add { } remove { } } public Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken) { // by the default, we are always fully loaded return Task.CompletedTask; } public Task<bool> IsFullyLoadedAsync(CancellationToken cancellationToken) { // by the default, we are always fully loaded return SpecializedTasks.True; } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Workspaces/Core/Portable/Rename/RenameEntityKind.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.Rename { public enum RenameEntityKind { /// <summary> /// mentions that the result is for the base symbol of the rename /// </summary> BaseSymbol = 0, /// <summary> /// mentions that the result is for the overloaded symbols of the rename /// </summary> OverloadedSymbols = 1 } }
// 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.Rename { public enum RenameEntityKind { /// <summary> /// mentions that the result is for the base symbol of the rename /// </summary> BaseSymbol = 0, /// <summary> /// mentions that the result is for the overloaded symbols of the rename /// </summary> OverloadedSymbols = 1 } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/CSharp/Portable/ConvertTupleToStruct/CSharpConvertTupleToStructCodeRefactoringProvider.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.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertTupleToStruct; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct { [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportLanguageService(typeof(IConvertTupleToStructCodeRefactoringProvider), LanguageNames.CSharp)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct), Shared] internal class CSharpConvertTupleToStructCodeRefactoringProvider : AbstractConvertTupleToStructCodeRefactoringProvider< ExpressionSyntax, NameSyntax, IdentifierNameSyntax, LiteralExpressionSyntax, ObjectCreationExpressionSyntax, TupleExpressionSyntax, ArgumentSyntax, TupleTypeSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpConvertTupleToStructCodeRefactoringProvider() { } protected override ArgumentSyntax GetArgumentWithChangedName(ArgumentSyntax argument, string name) => argument.WithNameColon(ChangeName(argument.NameColon, name)); private static NameColonSyntax? ChangeName(NameColonSyntax? nameColon, string name) { if (nameColon == null) { return null; } var newName = SyntaxFactory.IdentifierName(name).WithTriviaFrom(nameColon.Name); return nameColon.WithName(newName); } } }
// 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.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertTupleToStruct; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct { [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportLanguageService(typeof(IConvertTupleToStructCodeRefactoringProvider), LanguageNames.CSharp)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct), Shared] internal class CSharpConvertTupleToStructCodeRefactoringProvider : AbstractConvertTupleToStructCodeRefactoringProvider< ExpressionSyntax, NameSyntax, IdentifierNameSyntax, LiteralExpressionSyntax, ObjectCreationExpressionSyntax, TupleExpressionSyntax, ArgumentSyntax, TupleTypeSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpConvertTupleToStructCodeRefactoringProvider() { } protected override ArgumentSyntax GetArgumentWithChangedName(ArgumentSyntax argument, string name) => argument.WithNameColon(ChangeName(argument.NameColon, name)); private static NameColonSyntax? ChangeName(NameColonSyntax? nameColon, string name) { if (nameColon == null) { return null; } var newName = SyntaxFactory.IdentifierName(name).WithTriviaFrom(nameColon.Name); return nameColon.WithName(newName); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/EditorFeatures/CSharpTest2/Recommendations/ExternKeywordRecommenderTests.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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ExternKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement() { await VerifyKeywordAsync( @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration() { await VerifyKeywordAsync( @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInEmptyStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterStaticInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesInSwitchCase(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"switch (c) { case 0: [Goo] $$ }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesAndStaticInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndReturnStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ return x;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndLocalDeclarationStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ x y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndAwaitExpression(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ await bar;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndAssignmentStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Goo] $$ y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndCallStatement1(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Goo] $$ bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndCallStatement2(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Goo1] [Goo2] $$ bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterExternInStatement(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"extern $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExternKeyword() => await VerifyAbsenceAsync(@"extern $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousExternAlias() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideNamespace() { await VerifyKeywordAsync( @"namespace N { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N;$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExternKeyword_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { extern $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousExternAlias_InsideNamespace() { await VerifyKeywordAsync( @"namespace N { extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMember_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNamespace_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() { await VerifyAbsenceAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExtern() { await VerifyAbsenceAsync( @"class C { extern $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"class C { public $$"); } } }
// 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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ExternKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement() { await VerifyKeywordAsync( @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration() { await VerifyKeywordAsync( @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInEmptyStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterStaticInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesInSwitchCase(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"switch (c) { case 0: [Goo] $$ }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesAndStaticInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndReturnStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ return x;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndLocalDeclarationStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ x y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndAwaitExpression(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ await bar;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndAssignmentStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Goo] $$ y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndCallStatement1(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Goo] $$ bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndCallStatement2(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Goo1] [Goo2] $$ bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterExternInStatement(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"extern $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExternKeyword() => await VerifyAbsenceAsync(@"extern $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousExternAlias() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideNamespace() { await VerifyKeywordAsync( @"namespace N { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N;$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExternKeyword_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { extern $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousExternAlias_InsideNamespace() { await VerifyKeywordAsync( @"namespace N { extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMember_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNamespace_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() { await VerifyAbsenceAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExtern() { await VerifyAbsenceAsync( @"class C { extern $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"class C { public $$"); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./azure-pipelines-integration-corehost.yml
# Separate pipeline from normal integration CI to allow branches to change legs # Branches that trigger a build on commit trigger: - main - main-vs-deps - release/* - features/* - demos/* # Branches that are allowed to trigger a build via /azp run. # Automatic building of all PRs is disabled in the pipeline's trigger page. # See https://docs.microsoft.com/en-us/azure/devops/pipelines/repos/github?view=azure-devops&tabs=yaml#comment-triggers pr: - main - main-vs-deps - release/* - features/* - demos/* variables: - name: XUNIT_LOGS value: $(Build.SourcesDirectory)\artifacts\log\$(_configuration) jobs: - job: VS_Integration_CoreHost pool: name: NetCore1ESPool-Public demands: ImageOverride -equals $(queueName) strategy: maxParallel: 2 matrix: debug: _configuration: Debug release: _configuration: Release timeoutInMinutes: 135 steps: - template: eng/pipelines/test-integration-job.yml parameters: configuration: $(_configuration) oop64bit: true oopCoreClr: true
# Separate pipeline from normal integration CI to allow branches to change legs # Branches that trigger a build on commit trigger: - main - main-vs-deps - release/* - features/* - demos/* # Branches that are allowed to trigger a build via /azp run. # Automatic building of all PRs is disabled in the pipeline's trigger page. # See https://docs.microsoft.com/en-us/azure/devops/pipelines/repos/github?view=azure-devops&tabs=yaml#comment-triggers pr: - main - main-vs-deps - release/* - features/* - demos/* variables: - name: XUNIT_LOGS value: $(Build.SourcesDirectory)\artifacts\log\$(_configuration) jobs: - job: VS_Integration_CoreHost pool: name: NetCore1ESPool-Public demands: ImageOverride -equals $(queueName) strategy: maxParallel: 2 matrix: debug: _configuration: Debug release: _configuration: Release timeoutInMinutes: 135 steps: - template: eng/pipelines/test-integration-job.yml parameters: configuration: $(_configuration) oop64bit: true oopCoreClr: true
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/EditorFeatures/Test/Diagnostics/IDEDiagnosticIDUniquenessTest.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.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public class IDEDiagnosticIDUniquenessTest { [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)] public void UniqueIDEDiagnosticIds() { var type = typeof(IDEDiagnosticIds); var listOfIDEDiagnosticIds = type.GetFields().Select(x => x.GetValue(null).ToString()).ToList(); Assert.Equal(listOfIDEDiagnosticIds.Count, listOfIDEDiagnosticIds.Distinct().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. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public class IDEDiagnosticIDUniquenessTest { [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)] public void UniqueIDEDiagnosticIds() { var type = typeof(IDEDiagnosticIds); var listOfIDEDiagnosticIds = type.GetFields().Select(x => x.GetValue(null).ToString()).ToList(); Assert.Equal(listOfIDEDiagnosticIds.Count, listOfIDEDiagnosticIds.Distinct().Count()); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Tools/ExternalAccess/OmniSharp/Internal/ExtractClass/OmniSharpExtractClassOptionsService.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.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.ExtractClass; using Microsoft.CodeAnalysis.ExtractClass; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Internal.ExtractClass { [Shared] [ExportWorkspaceService(typeof(IExtractClassOptionsService))] internal class OmniSharpExtractClassOptionsService : IExtractClassOptionsService { private readonly IOmniSharpExtractClassOptionsService _omniSharpExtractClassOptionsService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OmniSharpExtractClassOptionsService(IOmniSharpExtractClassOptionsService omniSharpExtractClassOptionsService) { _omniSharpExtractClassOptionsService = omniSharpExtractClassOptionsService; } public async Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalType, ISymbol? selectedMember) { var result = await _omniSharpExtractClassOptionsService.GetExtractClassOptionsAsync(document, originalType, selectedMember).ConfigureAwait(false); return result == null ? null : new ExtractClassOptions( result.FileName, result.TypeName, result.SameFile, result.MemberAnalysisResults.SelectAsArray(m => new ExtractClassMemberAnalysisResult(m.Member, m.MakeAbstract))); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.ExtractClass; using Microsoft.CodeAnalysis.ExtractClass; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Internal.ExtractClass { [Shared] [ExportWorkspaceService(typeof(IExtractClassOptionsService))] internal class OmniSharpExtractClassOptionsService : IExtractClassOptionsService { private readonly IOmniSharpExtractClassOptionsService _omniSharpExtractClassOptionsService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OmniSharpExtractClassOptionsService(IOmniSharpExtractClassOptionsService omniSharpExtractClassOptionsService) { _omniSharpExtractClassOptionsService = omniSharpExtractClassOptionsService; } public async Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalType, ISymbol? selectedMember) { var result = await _omniSharpExtractClassOptionsService.GetExtractClassOptionsAsync(document, originalType, selectedMember).ConfigureAwait(false); return result == null ? null : new ExtractClassOptions( result.FileName, result.TypeName, result.SameFile, result.MemberAnalysisResults.SelectAsArray(m => new ExtractClassMemberAnalysisResult(m.Member, m.MakeAbstract))); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/VBTargetLibraryType.vb
' 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.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop <Flags()> Friend Enum VBTargetLibraryType TLB_AutoDetect = 0 TLB_Desktop = 1 TLB_Starlite = 2 End Enum End Namespace
' 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.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop <Flags()> Friend Enum VBTargetLibraryType TLB_AutoDetect = 0 TLB_Desktop = 1 TLB_Starlite = 2 End Enum End Namespace
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Workspaces/MSBuildTest/Resources/Dlls/CSharpProject.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL/N! & @@ @&K@p` 0&  H.text  `.rsrcp@ @@.reloc `@B&HX ( *BSJB v4.0.30319l#~,x#Strings#US#GUID#BlobG %3 F?eS|SSSSSS SX9l9zSS? 9Y(P M MM!M)M1M9MAMIMQMYMaMiMqMyMMM M . #.6.6.#<.+#.3K.;6.K6.Sl.c.k.s.{.(6<Module>CSharpProject.dllCSharpClassCSharpProjectmscorlibSystemObject.ctorSystem.ReflectionAssemblyTitleAttributeAssemblyDescriptionAttributeAssemblyConfigurationAttributeAssemblyCompanyAttributeAssemblyProductAttributeAssemblyCopyrightAttributeAssemblyTrademarkAttributeAssemblyCultureAttributeSystem.Runtime.InteropServicesComVisibleAttributeGuidAttributeAssemblyVersionAttributeAssemblyFileVersionAttributeSystem.Runtime.VersioningTargetFrameworkAttributeSystem.DiagnosticsDebuggableAttributeDebuggingModesSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttribute mpalGjшz\V4    A  CSharpProject Microsoft Copyright © Microsoft 2011)$c5fab32d-a9d9-4028-9b8c-c9566d69c57c 1.0.0.0G.NETFramework,Version=v4.0TFrameworkDisplayName.NET Framework 4TWrapNonExceptionThrows/NRL&LRSDSLzJ` Fc:\TestSolution\CSharpProject\obj\Debug\CSharpProject.pdb&& &_CorDllMainmscoree.dll% @0HX@4VS_VERSION_INFO?DVarFileInfo$TranslationxStringFileInfoT000004b04 CompanyNameMicrosoftDFileDescriptionCSharpProject0FileVersion1.0.0.0DInternalNameCSharpProject.dll\LegalCopyrightCopyright Microsoft 2011LOriginalFilenameCSharpProject.dll<ProductNameCSharpProject4ProductVersion1.0.0.08Assembly Version1.0.0.0 6
MZ@ !L!This program cannot be run in DOS mode. $PEL/N! & @@ @&K@p` 0&  H.text  `.rsrcp@ @@.reloc `@B&HX ( *BSJB v4.0.30319l#~,x#Strings#US#GUID#BlobG %3 F?eS|SSSSSS SX9l9zSS? 9Y(P M MM!M)M1M9MAMIMQMYMaMiMqMyMMM M . #.6.6.#<.+#.3K.;6.K6.Sl.c.k.s.{.(6<Module>CSharpProject.dllCSharpClassCSharpProjectmscorlibSystemObject.ctorSystem.ReflectionAssemblyTitleAttributeAssemblyDescriptionAttributeAssemblyConfigurationAttributeAssemblyCompanyAttributeAssemblyProductAttributeAssemblyCopyrightAttributeAssemblyTrademarkAttributeAssemblyCultureAttributeSystem.Runtime.InteropServicesComVisibleAttributeGuidAttributeAssemblyVersionAttributeAssemblyFileVersionAttributeSystem.Runtime.VersioningTargetFrameworkAttributeSystem.DiagnosticsDebuggableAttributeDebuggingModesSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttribute mpalGjшz\V4    A  CSharpProject Microsoft Copyright © Microsoft 2011)$c5fab32d-a9d9-4028-9b8c-c9566d69c57c 1.0.0.0G.NETFramework,Version=v4.0TFrameworkDisplayName.NET Framework 4TWrapNonExceptionThrows/NRL&LRSDSLzJ` Fc:\TestSolution\CSharpProject\obj\Debug\CSharpProject.pdb&& &_CorDllMainmscoree.dll% @0HX@4VS_VERSION_INFO?DVarFileInfo$TranslationxStringFileInfoT000004b04 CompanyNameMicrosoftDFileDescriptionCSharpProject0FileVersion1.0.0.0DInternalNameCSharpProject.dll\LegalCopyrightCopyright Microsoft 2011LOriginalFilenameCSharpProject.dll<ProductNameCSharpProject4ProductVersion1.0.0.08Assembly Version1.0.0.0 6
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/LanguageServer/Protocol/Handler/Definitions/GoToDefinitionHandler.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MetadataAsSource; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentDefinitionName)] internal class GoToDefinitionHandler : AbstractGoToDefinitionHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService) : base(metadataAsSourceFileService) { } public override string Method => LSP.Methods.TextDocumentDefinitionName; public override Task<LSP.Location[]?> HandleRequestAsync(LSP.TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) => GetDefinitionAsync(request, typeOnly: false, context, 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MetadataAsSource; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentDefinitionName)] internal class GoToDefinitionHandler : AbstractGoToDefinitionHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToDefinitionHandler(IMetadataAsSourceFileService metadataAsSourceFileService) : base(metadataAsSourceFileService) { } public override string Method => LSP.Methods.TextDocumentDefinitionName; public override Task<LSP.Location[]?> HandleRequestAsync(LSP.TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) => GetDefinitionAsync(request, typeOnly: false, context, cancellationToken); } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/DisplayClassInstance.vb
' 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. Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend MustInherit Class DisplayClassInstance Friend MustOverride ReadOnly Property ContainingSymbol As Symbol Friend MustOverride ReadOnly Property Type As TypeSymbol Friend MustOverride Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Friend MustOverride Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Friend Function GetDebuggerDisplay(fields As ConsList(Of FieldSymbol)) As String Return GetDebuggerDisplay(GetInstanceName(), fields) End Function Private Shared Function GetDebuggerDisplay(expr As String, fields As ConsList(Of FieldSymbol)) As String Return If(fields.Any(), $"{GetDebuggerDisplay(expr, fields.Tail)}.{fields.Head.Name}", expr) End Function Protected MustOverride Function GetInstanceName() As String End Class Friend NotInheritable Class DisplayClassInstanceFromLocal Inherits DisplayClassInstance Friend ReadOnly Local As EELocalSymbol Friend Sub New(local As EELocalSymbol) Debug.Assert(Not local.IsByRef) Debug.Assert(local.DeclarationKind = LocalDeclarationKind.Variable) Me.Local = local End Sub Friend Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me.Local.ContainingSymbol End Get End Property Friend Overrides ReadOnly Property Type As TypeSymbol Get Return Me.Local.Type End Get End Property Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Dim otherInstance = DirectCast(Me.Local.ToOtherMethod(method, typeMap), EELocalSymbol) Return New DisplayClassInstanceFromLocal(otherInstance) End Function Friend Overrides Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Return New BoundLocal(syntax, Me.Local, Me.Local.Type).MakeCompilerGenerated() End Function Protected Overrides Function GetInstanceName() As String Return Local.Name End Function End Class Friend NotInheritable Class DisplayClassInstanceFromParameter Inherits DisplayClassInstance Friend ReadOnly Parameter As ParameterSymbol Friend Sub New(parameter As ParameterSymbol) Debug.Assert(parameter IsNot Nothing) Debug.Assert(parameter.Name.Equals("Me", StringComparison.Ordinal) OrElse parameter.Name.IndexOf("$Me", StringComparison.Ordinal) >= 0 OrElse parameter.Name.IndexOf("$It", StringComparison.Ordinal) >= 0) Me.Parameter = parameter End Sub Friend Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me.Parameter.ContainingSymbol End Get End Property Friend Overrides ReadOnly Property Type As TypeSymbol Get Return Me.Parameter.Type End Get End Property Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Debug.Assert(method.IsShared) Dim otherOrdinal = If(Me.ContainingSymbol.IsShared, Me.Parameter.Ordinal, Me.Parameter.Ordinal + 1) Dim otherParameter = method.Parameters(otherOrdinal) Return New DisplayClassInstanceFromParameter(otherParameter) End Function Friend Overrides Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Return New BoundParameter(syntax, Me.Parameter, Me.Parameter.Type).MakeCompilerGenerated() End Function Protected Overrides Function GetInstanceName() As String Return Parameter.Name End Function End Class End Namespace
' 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. Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend MustInherit Class DisplayClassInstance Friend MustOverride ReadOnly Property ContainingSymbol As Symbol Friend MustOverride ReadOnly Property Type As TypeSymbol Friend MustOverride Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Friend MustOverride Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Friend Function GetDebuggerDisplay(fields As ConsList(Of FieldSymbol)) As String Return GetDebuggerDisplay(GetInstanceName(), fields) End Function Private Shared Function GetDebuggerDisplay(expr As String, fields As ConsList(Of FieldSymbol)) As String Return If(fields.Any(), $"{GetDebuggerDisplay(expr, fields.Tail)}.{fields.Head.Name}", expr) End Function Protected MustOverride Function GetInstanceName() As String End Class Friend NotInheritable Class DisplayClassInstanceFromLocal Inherits DisplayClassInstance Friend ReadOnly Local As EELocalSymbol Friend Sub New(local As EELocalSymbol) Debug.Assert(Not local.IsByRef) Debug.Assert(local.DeclarationKind = LocalDeclarationKind.Variable) Me.Local = local End Sub Friend Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me.Local.ContainingSymbol End Get End Property Friend Overrides ReadOnly Property Type As TypeSymbol Get Return Me.Local.Type End Get End Property Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Dim otherInstance = DirectCast(Me.Local.ToOtherMethod(method, typeMap), EELocalSymbol) Return New DisplayClassInstanceFromLocal(otherInstance) End Function Friend Overrides Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Return New BoundLocal(syntax, Me.Local, Me.Local.Type).MakeCompilerGenerated() End Function Protected Overrides Function GetInstanceName() As String Return Local.Name End Function End Class Friend NotInheritable Class DisplayClassInstanceFromParameter Inherits DisplayClassInstance Friend ReadOnly Parameter As ParameterSymbol Friend Sub New(parameter As ParameterSymbol) Debug.Assert(parameter IsNot Nothing) Debug.Assert(parameter.Name.Equals("Me", StringComparison.Ordinal) OrElse parameter.Name.IndexOf("$Me", StringComparison.Ordinal) >= 0 OrElse parameter.Name.IndexOf("$It", StringComparison.Ordinal) >= 0) Me.Parameter = parameter End Sub Friend Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me.Parameter.ContainingSymbol End Get End Property Friend Overrides ReadOnly Property Type As TypeSymbol Get Return Me.Parameter.Type End Get End Property Friend Overrides Function ToOtherMethod(method As MethodSymbol, typeMap As TypeSubstitution) As DisplayClassInstance Debug.Assert(method.IsShared) Dim otherOrdinal = If(Me.ContainingSymbol.IsShared, Me.Parameter.Ordinal, Me.Parameter.Ordinal + 1) Dim otherParameter = method.Parameters(otherOrdinal) Return New DisplayClassInstanceFromParameter(otherParameter) End Function Friend Overrides Function ToBoundExpression(syntax As SyntaxNode) As BoundExpression Return New BoundParameter(syntax, Me.Parameter, Me.Parameter.Type).MakeCompilerGenerated() End Function Protected Overrides Function GetInstanceName() As String Return Parameter.Name End Function End Class End Namespace
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Core/Test/Progression/VisualBasicSymbolLabelTests.vb
' 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. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression <UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)> Public Class VisualBasicSymbolLabelTests <WpfFact, WorkItem(545008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545008")> Public Async Function TestMethodWithOptionalParameter() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj"> <Document FilePath="Z:\Project.vb"> Class C Sub $$S(Optional i As Integer = 42) End Sub End Class </Document> </Project> </Workspace>) Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "S([Integer])", "C.S([Integer])") End Using End Function <WpfFact, WorkItem(545009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545009")> Public Async Function TestMethodWithByRefParameter() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj"> <Document FilePath="Z:\Project.vb"> Class C Sub $$S(ByRef i As Integer) End Sub End Class </Document> </Project> </Workspace>) Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "S(ByRef Integer)", "C.S(ByRef Integer)") End Using End Function <WpfFact, WorkItem(545017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545017")> Public Async Function TestEnumMember() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj"> <Document FilePath="Z:\Project.vb"> Enum E $$M End Enum </Document> </Project> </Workspace>) Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "M", "E.M") End Using End Function <WpfFact, WorkItem(608256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608256")> Public Async Function TestGenericType() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj"> <Document FilePath="Z:\Project.vb"> Class $$C(Of T) End Class </Document> </Project> </Workspace>) Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "C(Of T)", "C(Of T)") End Using End Function End Class End Namespace
' 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. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression <UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)> Public Class VisualBasicSymbolLabelTests <WpfFact, WorkItem(545008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545008")> Public Async Function TestMethodWithOptionalParameter() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj"> <Document FilePath="Z:\Project.vb"> Class C Sub $$S(Optional i As Integer = 42) End Sub End Class </Document> </Project> </Workspace>) Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "S([Integer])", "C.S([Integer])") End Using End Function <WpfFact, WorkItem(545009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545009")> Public Async Function TestMethodWithByRefParameter() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj"> <Document FilePath="Z:\Project.vb"> Class C Sub $$S(ByRef i As Integer) End Sub End Class </Document> </Project> </Workspace>) Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "S(ByRef Integer)", "C.S(ByRef Integer)") End Using End Function <WpfFact, WorkItem(545017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545017")> Public Async Function TestEnumMember() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj"> <Document FilePath="Z:\Project.vb"> Enum E $$M End Enum </Document> </Project> </Workspace>) Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "M", "E.M") End Using End Function <WpfFact, WorkItem(608256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608256")> Public Async Function TestGenericType() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="Visual Basic" CommonReferences="true" FilePath="Z:\Project.vbproj"> <Document FilePath="Z:\Project.vb"> Class $$C(Of T) End Class </Document> </Project> </Workspace>) Await testState.AssertMarkedSymbolLabelIsAsync(GraphCommandDefinition.Contains.Id, "C(Of T)", "C(Of T)") End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/Portable/Desktop/AssemblyPortabilityPolicy.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.Xml; namespace Microsoft.CodeAnalysis { /// <summary> /// Policy to be used when matching assembly reference to an assembly definition across platforms. /// </summary> internal struct AssemblyPortabilityPolicy : IEquatable<AssemblyPortabilityPolicy> { // 7cec85d7bea7798e (System, System.Core) public readonly bool SuppressSilverlightPlatformAssembliesPortability; // 31bf3856ad364e35 (Microsoft.VisualBasic, System.ComponentModel.Composition) public readonly bool SuppressSilverlightLibraryAssembliesPortability; public AssemblyPortabilityPolicy( bool suppressSilverlightPlatformAssembliesPortability, bool suppressSilverlightLibraryAssembliesPortability) { this.SuppressSilverlightLibraryAssembliesPortability = suppressSilverlightLibraryAssembliesPortability; this.SuppressSilverlightPlatformAssembliesPortability = suppressSilverlightPlatformAssembliesPortability; } public override bool Equals(object obj) { return obj is AssemblyPortabilityPolicy && Equals((AssemblyPortabilityPolicy)obj); } public bool Equals(AssemblyPortabilityPolicy other) { return this.SuppressSilverlightLibraryAssembliesPortability == other.SuppressSilverlightLibraryAssembliesPortability && this.SuppressSilverlightPlatformAssembliesPortability == other.SuppressSilverlightPlatformAssembliesPortability; } public override int GetHashCode() { return (this.SuppressSilverlightLibraryAssembliesPortability ? 1 : 0) | (this.SuppressSilverlightPlatformAssembliesPortability ? 2 : 0); } private static bool ReadToChild(XmlReader reader, int depth, string elementName, string elementNamespace = "") { return reader.ReadToDescendant(elementName, elementNamespace) && reader.Depth == depth; } private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit, }; internal static AssemblyPortabilityPolicy LoadFromXml(Stream input) { // Note: Unlike Fusion XML reader the XmlReader doesn't allow whitespace in front of <?xml version=""1.0"" encoding=""utf-8"" ?> const string ns = "urn:schemas-microsoft-com:asm.v1"; using (XmlReader xml = XmlReader.Create(input, s_xmlSettings)) { if (!ReadToChild(xml, 0, "configuration") || !ReadToChild(xml, 1, "runtime") || !ReadToChild(xml, 2, "assemblyBinding", ns) || !ReadToChild(xml, 3, "supportPortability", ns)) { return default(AssemblyPortabilityPolicy); } // 31bf3856ad364e35 bool suppressLibrary = false; // 7cec85d7bea7798e bool suppressPlatform = false; do { // see CNodeFactory::ProcessSupportPortabilityTag in fusion\inc\nodefact.cpp for details // - unrecognized attributes ignored. // - syntax errors within tags causes this tag to be ignored (but not reject entire app.config) // - multiple <supportPortability> tags ok (if two specify same PKT, all but (implementation defined) one ignored.) string pkt = xml.GetAttribute("PKT"); string enableAttribute = xml.GetAttribute("enable"); bool? enable = string.Equals(enableAttribute, "false", StringComparison.OrdinalIgnoreCase) ? false : string.Equals(enableAttribute, "true", StringComparison.OrdinalIgnoreCase) ? true : (bool?)null; if (enable != null) { if (string.Equals(pkt, "31bf3856ad364e35", StringComparison.OrdinalIgnoreCase)) { suppressLibrary = !enable.Value; } else if (string.Equals(pkt, "7cec85d7bea7798e", StringComparison.OrdinalIgnoreCase)) { suppressPlatform = !enable.Value; } } } while (xml.ReadToNextSibling("supportPortability", ns)); return new AssemblyPortabilityPolicy(suppressPlatform, suppressLibrary); } } } }
// 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.Xml; namespace Microsoft.CodeAnalysis { /// <summary> /// Policy to be used when matching assembly reference to an assembly definition across platforms. /// </summary> internal struct AssemblyPortabilityPolicy : IEquatable<AssemblyPortabilityPolicy> { // 7cec85d7bea7798e (System, System.Core) public readonly bool SuppressSilverlightPlatformAssembliesPortability; // 31bf3856ad364e35 (Microsoft.VisualBasic, System.ComponentModel.Composition) public readonly bool SuppressSilverlightLibraryAssembliesPortability; public AssemblyPortabilityPolicy( bool suppressSilverlightPlatformAssembliesPortability, bool suppressSilverlightLibraryAssembliesPortability) { this.SuppressSilverlightLibraryAssembliesPortability = suppressSilverlightLibraryAssembliesPortability; this.SuppressSilverlightPlatformAssembliesPortability = suppressSilverlightPlatformAssembliesPortability; } public override bool Equals(object obj) { return obj is AssemblyPortabilityPolicy && Equals((AssemblyPortabilityPolicy)obj); } public bool Equals(AssemblyPortabilityPolicy other) { return this.SuppressSilverlightLibraryAssembliesPortability == other.SuppressSilverlightLibraryAssembliesPortability && this.SuppressSilverlightPlatformAssembliesPortability == other.SuppressSilverlightPlatformAssembliesPortability; } public override int GetHashCode() { return (this.SuppressSilverlightLibraryAssembliesPortability ? 1 : 0) | (this.SuppressSilverlightPlatformAssembliesPortability ? 2 : 0); } private static bool ReadToChild(XmlReader reader, int depth, string elementName, string elementNamespace = "") { return reader.ReadToDescendant(elementName, elementNamespace) && reader.Depth == depth; } private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit, }; internal static AssemblyPortabilityPolicy LoadFromXml(Stream input) { // Note: Unlike Fusion XML reader the XmlReader doesn't allow whitespace in front of <?xml version=""1.0"" encoding=""utf-8"" ?> const string ns = "urn:schemas-microsoft-com:asm.v1"; using (XmlReader xml = XmlReader.Create(input, s_xmlSettings)) { if (!ReadToChild(xml, 0, "configuration") || !ReadToChild(xml, 1, "runtime") || !ReadToChild(xml, 2, "assemblyBinding", ns) || !ReadToChild(xml, 3, "supportPortability", ns)) { return default(AssemblyPortabilityPolicy); } // 31bf3856ad364e35 bool suppressLibrary = false; // 7cec85d7bea7798e bool suppressPlatform = false; do { // see CNodeFactory::ProcessSupportPortabilityTag in fusion\inc\nodefact.cpp for details // - unrecognized attributes ignored. // - syntax errors within tags causes this tag to be ignored (but not reject entire app.config) // - multiple <supportPortability> tags ok (if two specify same PKT, all but (implementation defined) one ignored.) string pkt = xml.GetAttribute("PKT"); string enableAttribute = xml.GetAttribute("enable"); bool? enable = string.Equals(enableAttribute, "false", StringComparison.OrdinalIgnoreCase) ? false : string.Equals(enableAttribute, "true", StringComparison.OrdinalIgnoreCase) ? true : (bool?)null; if (enable != null) { if (string.Equals(pkt, "31bf3856ad364e35", StringComparison.OrdinalIgnoreCase)) { suppressLibrary = !enable.Value; } else if (string.Equals(pkt, "7cec85d7bea7798e", StringComparison.OrdinalIgnoreCase)) { suppressPlatform = !enable.Value; } } } while (xml.ReadToNextSibling("supportPortability", ns)); return new AssemblyPortabilityPolicy(suppressPlatform, suppressLibrary); } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/EditorFeatures/CSharpTest2/Recommendations/ManagedKeywordRecommenderTests.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ManagedKeywordRecommenderTests : RecommenderTests { private readonly ManagedKeywordRecommender _recommender = new ManagedKeywordRecommender(); public ManagedKeywordRecommenderTests() { this.keywordText = "managed"; this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerDeclaration() { await VerifyKeywordAsync( @"class Test { unsafe void N() { delegate* $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerDeclarationTouchingAsterisk() { await VerifyKeywordAsync( @"class Test { unsafe void N() { delegate*$$"); } } }
// 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ManagedKeywordRecommenderTests : RecommenderTests { private readonly ManagedKeywordRecommender _recommender = new ManagedKeywordRecommender(); public ManagedKeywordRecommenderTests() { this.keywordText = "managed"; this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerDeclaration() { await VerifyKeywordAsync( @"class Test { unsafe void N() { delegate* $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerDeclarationTouchingAsterisk() { await VerifyKeywordAsync( @"class Test { unsafe void N() { delegate*$$"); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/Portable/VersionHelper.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.Globalization; namespace Microsoft.CodeAnalysis { internal static class VersionHelper { /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' build [ '.' revision ] ] ]". /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="version">If parsing succeeds, the parsed version. Otherwise a version that represents as much of the input as could be parsed successfully.</param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> internal static bool TryParse(string s, out Version version) { return TryParse(s, allowWildcard: false, maxValue: ushort.MaxValue, allowPartialParse: true, version: out version); } /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' ( '*' | ( build [ '.' ( '*' | revision ) ] ) ) ] ]" /// as accepted by System.Reflection.AssemblyVersionAttribute. /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="allowWildcard">Indicates whether or not a wildcard is accepted as the terminal component.</param> /// <param name="version"> /// If parsing succeeded, the parsed version. Otherwise a version instance with all parts set to zero. /// If <paramref name="s"/> contains * the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> internal static bool TryParseAssemblyVersion(string s, bool allowWildcard, out Version version) { return TryParse(s, allowWildcard: allowWildcard, maxValue: ushort.MaxValue - 1, allowPartialParse: false, version: out version); } /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' ( '*' | ( build [ '.' ( '*' | revision ) ] ) ) ] ]" /// as accepted by System.Reflection.AssemblyVersionAttribute. /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="allowWildcard">Indicates whether or not we're parsing an assembly version string. If so, wildcards are accepted and each component must be less than 65535.</param> /// <param name="maxValue">The maximum value that a version component may have.</param> /// <param name="allowPartialParse">Allow the parsing of version elements where invalid characters exist. e.g. 1.2.2a.1</param> /// <param name="version"> /// If parsing succeeded, the parsed version. When <paramref name="allowPartialParse"/> is true a version with values up to the first invalid character set. Otherwise a version with all parts set to zero. /// If <paramref name="s"/> contains * and wildcard is allowed the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> private static bool TryParse(string s, bool allowWildcard, ushort maxValue, bool allowPartialParse, out Version version) { Debug.Assert(!allowWildcard || maxValue < ushort.MaxValue); if (string.IsNullOrWhiteSpace(s)) { version = AssemblyIdentity.NullVersion; return false; } string[] elements = s.Split('.'); // If the wildcard is being used, the first two elements must be specified explicitly, and // the last must be a exactly single asterisk without whitespace. bool hasWildcard = allowWildcard && elements[elements.Length - 1] == "*"; if ((hasWildcard && elements.Length < 3) || elements.Length > 4) { version = AssemblyIdentity.NullVersion; return false; } ushort[] values = new ushort[4]; int lastExplicitValue = hasWildcard ? elements.Length - 1 : elements.Length; bool parseError = false; for (int i = 0; i < lastExplicitValue; i++) { if (!ushort.TryParse(elements[i], NumberStyles.None, CultureInfo.InvariantCulture, out values[i]) || values[i] > maxValue) { if (!allowPartialParse) { version = AssemblyIdentity.NullVersion; return false; } parseError = true; if (string.IsNullOrWhiteSpace(elements[i])) { values[i] = 0; break; } if (values[i] > maxValue) { //The only way this can happen is if the value was 65536 //The old compiler would continue parsing from here values[i] = 0; continue; } bool invalidFormat = false; System.Numerics.BigInteger number = 0; //There could be an invalid character in the input so check for the presence of one and //parse up to that point. examples of invalid characters are alphas and punctuation for (var idx = 0; idx < elements[i].Length; idx++) { if (!char.IsDigit(elements[i][idx])) { invalidFormat = true; TryGetValue(elements[i].Substring(0, idx), out values[i]); break; } } if (!invalidFormat) { //if we made it here then there weren't any alpha or punctuation chars in the input so the //element is either greater than ushort.MaxValue or possibly a fullwidth unicode digit. if (TryGetValue(elements[i], out values[i])) { //For this scenario the old compiler would continue processing the remaining version elements //so continue processing continue; } } //Don't process any more of the version elements break; } } if (hasWildcard) { for (int i = lastExplicitValue; i < values.Length; i++) { values[i] = ushort.MaxValue; } } version = new Version(values[0], values[1], values[2], values[3]); return !parseError; } private static bool TryGetValue(string s, out ushort value) { System.Numerics.BigInteger number; if (System.Numerics.BigInteger.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out number)) { //The old compiler would take the 16 least significant bits and use their value as the output //so we'll do that too. value = (ushort)(number % 65536); return true; } //One case that will cause us to end up here is when the input is a Fullwidth unicode digit //so we'll always return zero value = 0; return false; } /// <summary> /// If build and/or revision numbers are 65535 they are replaced with time-based values. /// </summary> public static Version? GenerateVersionFromPatternAndCurrentTime(DateTime time, Version pattern) { if (pattern == null || pattern.Revision != ushort.MaxValue) { return pattern; } // MSDN doc on the attribute: // "The default build number increments daily. The default revision number is the number of seconds since midnight local time // (without taking into account time zone adjustments for daylight saving time), divided by 2." if (time == default(DateTime)) { time = DateTime.Now; } int revision = (int)time.TimeOfDay.TotalSeconds / 2; // 24 * 60 * 60 / 2 = 43200 < 65535 Debug.Assert(revision < ushort.MaxValue); if (pattern.Build == ushort.MaxValue) { TimeSpan days = time.Date - new DateTime(2000, 1, 1); int build = Math.Min(ushort.MaxValue, (int)days.TotalDays); return new Version(pattern.Major, pattern.Minor, (ushort)build, (ushort)revision); } else { return new Version(pattern.Major, pattern.Minor, pattern.Build, (ushort)revision); } } } }
// 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.Globalization; namespace Microsoft.CodeAnalysis { internal static class VersionHelper { /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' build [ '.' revision ] ] ]". /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="version">If parsing succeeds, the parsed version. Otherwise a version that represents as much of the input as could be parsed successfully.</param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> internal static bool TryParse(string s, out Version version) { return TryParse(s, allowWildcard: false, maxValue: ushort.MaxValue, allowPartialParse: true, version: out version); } /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' ( '*' | ( build [ '.' ( '*' | revision ) ] ) ) ] ]" /// as accepted by System.Reflection.AssemblyVersionAttribute. /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="allowWildcard">Indicates whether or not a wildcard is accepted as the terminal component.</param> /// <param name="version"> /// If parsing succeeded, the parsed version. Otherwise a version instance with all parts set to zero. /// If <paramref name="s"/> contains * the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> internal static bool TryParseAssemblyVersion(string s, bool allowWildcard, out Version version) { return TryParse(s, allowWildcard: allowWildcard, maxValue: ushort.MaxValue - 1, allowPartialParse: false, version: out version); } /// <summary> /// Parses a version string of the form "major [ '.' minor [ '.' ( '*' | ( build [ '.' ( '*' | revision ) ] ) ) ] ]" /// as accepted by System.Reflection.AssemblyVersionAttribute. /// </summary> /// <param name="s">The version string to parse.</param> /// <param name="allowWildcard">Indicates whether or not we're parsing an assembly version string. If so, wildcards are accepted and each component must be less than 65535.</param> /// <param name="maxValue">The maximum value that a version component may have.</param> /// <param name="allowPartialParse">Allow the parsing of version elements where invalid characters exist. e.g. 1.2.2a.1</param> /// <param name="version"> /// If parsing succeeded, the parsed version. When <paramref name="allowPartialParse"/> is true a version with values up to the first invalid character set. Otherwise a version with all parts set to zero. /// If <paramref name="s"/> contains * and wildcard is allowed the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>. /// </param> /// <returns>True when parsing succeeds completely (i.e. every character in the string was consumed), false otherwise.</returns> private static bool TryParse(string s, bool allowWildcard, ushort maxValue, bool allowPartialParse, out Version version) { Debug.Assert(!allowWildcard || maxValue < ushort.MaxValue); if (string.IsNullOrWhiteSpace(s)) { version = AssemblyIdentity.NullVersion; return false; } string[] elements = s.Split('.'); // If the wildcard is being used, the first two elements must be specified explicitly, and // the last must be a exactly single asterisk without whitespace. bool hasWildcard = allowWildcard && elements[elements.Length - 1] == "*"; if ((hasWildcard && elements.Length < 3) || elements.Length > 4) { version = AssemblyIdentity.NullVersion; return false; } ushort[] values = new ushort[4]; int lastExplicitValue = hasWildcard ? elements.Length - 1 : elements.Length; bool parseError = false; for (int i = 0; i < lastExplicitValue; i++) { if (!ushort.TryParse(elements[i], NumberStyles.None, CultureInfo.InvariantCulture, out values[i]) || values[i] > maxValue) { if (!allowPartialParse) { version = AssemblyIdentity.NullVersion; return false; } parseError = true; if (string.IsNullOrWhiteSpace(elements[i])) { values[i] = 0; break; } if (values[i] > maxValue) { //The only way this can happen is if the value was 65536 //The old compiler would continue parsing from here values[i] = 0; continue; } bool invalidFormat = false; System.Numerics.BigInteger number = 0; //There could be an invalid character in the input so check for the presence of one and //parse up to that point. examples of invalid characters are alphas and punctuation for (var idx = 0; idx < elements[i].Length; idx++) { if (!char.IsDigit(elements[i][idx])) { invalidFormat = true; TryGetValue(elements[i].Substring(0, idx), out values[i]); break; } } if (!invalidFormat) { //if we made it here then there weren't any alpha or punctuation chars in the input so the //element is either greater than ushort.MaxValue or possibly a fullwidth unicode digit. if (TryGetValue(elements[i], out values[i])) { //For this scenario the old compiler would continue processing the remaining version elements //so continue processing continue; } } //Don't process any more of the version elements break; } } if (hasWildcard) { for (int i = lastExplicitValue; i < values.Length; i++) { values[i] = ushort.MaxValue; } } version = new Version(values[0], values[1], values[2], values[3]); return !parseError; } private static bool TryGetValue(string s, out ushort value) { System.Numerics.BigInteger number; if (System.Numerics.BigInteger.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out number)) { //The old compiler would take the 16 least significant bits and use their value as the output //so we'll do that too. value = (ushort)(number % 65536); return true; } //One case that will cause us to end up here is when the input is a Fullwidth unicode digit //so we'll always return zero value = 0; return false; } /// <summary> /// If build and/or revision numbers are 65535 they are replaced with time-based values. /// </summary> public static Version? GenerateVersionFromPatternAndCurrentTime(DateTime time, Version pattern) { if (pattern == null || pattern.Revision != ushort.MaxValue) { return pattern; } // MSDN doc on the attribute: // "The default build number increments daily. The default revision number is the number of seconds since midnight local time // (without taking into account time zone adjustments for daylight saving time), divided by 2." if (time == default(DateTime)) { time = DateTime.Now; } int revision = (int)time.TimeOfDay.TotalSeconds / 2; // 24 * 60 * 60 / 2 = 43200 < 65535 Debug.Assert(revision < ushort.MaxValue); if (pattern.Build == ushort.MaxValue) { TimeSpan days = time.Date - new DateTime(2000, 1, 1); int build = Math.Min(ushort.MaxValue, (int)days.TotalDays); return new Version(pattern.Major, pattern.Minor, (ushort)build, (ushort)revision); } else { return new Version(pattern.Major, pattern.Minor, pattern.Build, (ushort)revision); } } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Features/Core/Portable/EditAndContinue/Contracts/EditAndContinue/ManagedActiveStatementDebugInfo.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.EditAndContinue.Contracts { /// <summary> /// Active statement debug information retrieved from the runtime and the PDB. /// </summary> [DataContract] internal readonly struct ManagedActiveStatementDebugInfo { /// <summary> /// Creates a ManagedActiveStatementDebugInfo. /// </summary> /// <param name="activeInstruction">Instruction of the active statement that is being executed.</param> /// <param name="documentName">Document name as found in the PDB, if the active statement location was determined.</param> /// <param name="sourceSpan">Location of the closest non-hidden sequence point from the active statement.</param> /// <param name="flags">Active statement flags shared across all threads that own the active statement.</param> public ManagedActiveStatementDebugInfo( ManagedInstructionId activeInstruction, string? documentName, SourceSpan sourceSpan, ActiveStatementFlags flags) { ActiveInstruction = activeInstruction; DocumentName = documentName; SourceSpan = sourceSpan; Flags = flags; } /// <summary> /// The instruction of the active statement that is being executed. /// </summary> [DataMember(Name = "activeInstruction")] public ManagedInstructionId ActiveInstruction { get; } /// <summary> /// Document name as found in the PDB, or null if the debugger can't determine the location of the active statement. /// </summary> [DataMember(Name = "documentName")] public string? DocumentName { get; } /// <summary> /// Location of the closest non-hidden sequence point retrieved from the PDB, /// or default(<see cref="SourceSpan"/>) if the debugger can't determine the location of the active statement. /// </summary> [DataMember(Name = "sourceSpan")] public SourceSpan SourceSpan { get; } /// <summary> /// Aggregated across any threads that own the active instruction. /// </summary> [DataMember(Name = "flags")] public ActiveStatementFlags Flags { get; } public bool HasSourceLocation => DocumentName != 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.Runtime.Serialization; namespace Microsoft.CodeAnalysis.EditAndContinue.Contracts { /// <summary> /// Active statement debug information retrieved from the runtime and the PDB. /// </summary> [DataContract] internal readonly struct ManagedActiveStatementDebugInfo { /// <summary> /// Creates a ManagedActiveStatementDebugInfo. /// </summary> /// <param name="activeInstruction">Instruction of the active statement that is being executed.</param> /// <param name="documentName">Document name as found in the PDB, if the active statement location was determined.</param> /// <param name="sourceSpan">Location of the closest non-hidden sequence point from the active statement.</param> /// <param name="flags">Active statement flags shared across all threads that own the active statement.</param> public ManagedActiveStatementDebugInfo( ManagedInstructionId activeInstruction, string? documentName, SourceSpan sourceSpan, ActiveStatementFlags flags) { ActiveInstruction = activeInstruction; DocumentName = documentName; SourceSpan = sourceSpan; Flags = flags; } /// <summary> /// The instruction of the active statement that is being executed. /// </summary> [DataMember(Name = "activeInstruction")] public ManagedInstructionId ActiveInstruction { get; } /// <summary> /// Document name as found in the PDB, or null if the debugger can't determine the location of the active statement. /// </summary> [DataMember(Name = "documentName")] public string? DocumentName { get; } /// <summary> /// Location of the closest non-hidden sequence point retrieved from the PDB, /// or default(<see cref="SourceSpan"/>) if the debugger can't determine the location of the active statement. /// </summary> [DataMember(Name = "sourceSpan")] public SourceSpan SourceSpan { get; } /// <summary> /// Aggregated across any threads that own the active instruction. /// </summary> [DataMember(Name = "flags")] public ActiveStatementFlags Flags { get; } public bool HasSourceLocation => DocumentName != null; } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/Compilers/Core/Portable/PEWriter/PooledBlobBuilder.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.Reflection.Metadata; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; namespace Microsoft.Cci { internal sealed class PooledBlobBuilder : BlobBuilder, IDisposable { private const int PoolSize = 128; private const int ChunkSize = 1024; private static readonly ObjectPool<PooledBlobBuilder> s_chunkPool = new ObjectPool<PooledBlobBuilder>(() => new PooledBlobBuilder(ChunkSize), PoolSize); private PooledBlobBuilder(int size) : base(size) { } public static PooledBlobBuilder GetInstance(int size = ChunkSize) { // TODO: use size return s_chunkPool.Allocate(); } protected override BlobBuilder AllocateChunk(int minimalSize) { if (minimalSize <= ChunkSize) { return s_chunkPool.Allocate(); } return new BlobBuilder(minimalSize); } protected override void FreeChunk() { s_chunkPool.Free(this); } public new void Free() { base.Free(); } void IDisposable.Dispose() { Free(); } } }
// 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.Reflection.Metadata; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; namespace Microsoft.Cci { internal sealed class PooledBlobBuilder : BlobBuilder, IDisposable { private const int PoolSize = 128; private const int ChunkSize = 1024; private static readonly ObjectPool<PooledBlobBuilder> s_chunkPool = new ObjectPool<PooledBlobBuilder>(() => new PooledBlobBuilder(ChunkSize), PoolSize); private PooledBlobBuilder(int size) : base(size) { } public static PooledBlobBuilder GetInstance(int size = ChunkSize) { // TODO: use size return s_chunkPool.Allocate(); } protected override BlobBuilder AllocateChunk(int minimalSize) { if (minimalSize <= ChunkSize) { return s_chunkPool.Allocate(); } return new BlobBuilder(minimalSize); } protected override void FreeChunk() { s_chunkPool.Free(this); } public new void Free() { base.Free(); } void IDisposable.Dispose() { Free(); } } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/IntegrationTest/IntegrationService/IntegrationService.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.Concurrent; using System.Diagnostics; using System.Reflection; using System.Runtime.Remoting; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { /// <summary> /// Provides a means of executing code in the Visual Studio host process. /// </summary> /// <remarks> /// This object exists in the Visual Studio host and is marhsalled across the process boundary. /// </remarks> internal class IntegrationService : MarshalByRefObject { public string PortName { get; } /// <summary> /// The base Uri of the service. This resolves to a string such as <c>ipc://IntegrationService_{HostProcessId}"</c> /// </summary> public string BaseUri { get; } private readonly ConcurrentDictionary<string, ObjRef> _marshalledObjects = new ConcurrentDictionary<string, ObjRef>(); public IntegrationService() { AppContext.SetSwitch("Switch.System.Diagnostics.IgnorePortablePDBsInStackTraces", false); PortName = GetPortName(Process.GetCurrentProcess().Id); BaseUri = "ipc://" + this.PortName; } private static string GetPortName(int hostProcessId) { // Make the channel name well-known by using a static base and appending the process ID of the host return $"{nameof(IntegrationService)}_{{{hostProcessId}}}"; } public static IntegrationService GetInstanceFromHostProcess(Process hostProcess) { var uri = $"ipc://{GetPortName(hostProcess.Id)}/{typeof(IntegrationService).FullName}"; return (IntegrationService)Activator.GetObject(typeof(IntegrationService), uri); } public string? Execute(string assemblyFilePath, string typeFullName, string methodName) { var assembly = Assembly.LoadFrom(assemblyFilePath); var type = assembly.GetType(typeFullName); var methodInfo = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); var result = methodInfo.Invoke(null, null); if (methodInfo.ReturnType == typeof(void)) { return null; } // Create a unique URL for each object returned, so that we can communicate with each object individually var resultType = result.GetType(); var marshallableResult = (MarshalByRefObject)result; var objectUri = $"{resultType.FullName}_{Guid.NewGuid()}"; var marshalledObject = RemotingServices.Marshal(marshallableResult, objectUri, resultType); if (!_marshalledObjects.TryAdd(objectUri, marshalledObject)) { throw new InvalidOperationException($"An object with the specified URI has already been marshalled. (URI: {objectUri})"); } return objectUri; } // Ensure InProcComponents live forever public override object? InitializeLifetimeService() => 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.Concurrent; using System.Diagnostics; using System.Reflection; using System.Runtime.Remoting; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { /// <summary> /// Provides a means of executing code in the Visual Studio host process. /// </summary> /// <remarks> /// This object exists in the Visual Studio host and is marhsalled across the process boundary. /// </remarks> internal class IntegrationService : MarshalByRefObject { public string PortName { get; } /// <summary> /// The base Uri of the service. This resolves to a string such as <c>ipc://IntegrationService_{HostProcessId}"</c> /// </summary> public string BaseUri { get; } private readonly ConcurrentDictionary<string, ObjRef> _marshalledObjects = new ConcurrentDictionary<string, ObjRef>(); public IntegrationService() { AppContext.SetSwitch("Switch.System.Diagnostics.IgnorePortablePDBsInStackTraces", false); PortName = GetPortName(Process.GetCurrentProcess().Id); BaseUri = "ipc://" + this.PortName; } private static string GetPortName(int hostProcessId) { // Make the channel name well-known by using a static base and appending the process ID of the host return $"{nameof(IntegrationService)}_{{{hostProcessId}}}"; } public static IntegrationService GetInstanceFromHostProcess(Process hostProcess) { var uri = $"ipc://{GetPortName(hostProcess.Id)}/{typeof(IntegrationService).FullName}"; return (IntegrationService)Activator.GetObject(typeof(IntegrationService), uri); } public string? Execute(string assemblyFilePath, string typeFullName, string methodName) { var assembly = Assembly.LoadFrom(assemblyFilePath); var type = assembly.GetType(typeFullName); var methodInfo = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); var result = methodInfo.Invoke(null, null); if (methodInfo.ReturnType == typeof(void)) { return null; } // Create a unique URL for each object returned, so that we can communicate with each object individually var resultType = result.GetType(); var marshallableResult = (MarshalByRefObject)result; var objectUri = $"{resultType.FullName}_{Guid.NewGuid()}"; var marshalledObject = RemotingServices.Marshal(marshallableResult, objectUri, resultType); if (!_marshalledObjects.TryAdd(objectUri, marshalledObject)) { throw new InvalidOperationException($"An object with the specified URI has already been marshalled. (URI: {objectUri})"); } return objectUri; } // Ensure InProcComponents live forever public override object? InitializeLifetimeService() => null; } }
-1
dotnet/roslyn
56,432
When we're loading dependencies, don't require exact versions
When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
jasonmalinowski
"2021-09-16T01:19:09Z"
"2021-11-30T03:29:47Z"
e302aa0555624495ca1644c8488ddf33c6a65686
0bdc85394f139a23d8363a47635efa878112a95b
When we're loading dependencies, don't require exact versions. When we're loading analyzer dependencies, our current logic was to require the exact version that was requested from the loading assembly. This is problematic in a lot of cases where you would normally have a binding redirect to ensure assemblies load cleanly; by requiring exact versions we'd end up in diamond dependency cases where you couldn't practically produce an analyzer package that would cleanly load. While doing this change, @RikkiGibson and I noticed several other problems: 1. There was an errant cache that was left in the .NET Core implementation, which meant that we'd sometimes reuse assemblies even when we were able to load them correctly. This has also been fixed as a prerequisite to the main fix, since otherwise it was difficult to prove that the behavior changes here weren't also going to impact the .NET Core implementation. 2. There were some race conditions in the implementation. **REVIEWING COMMIT-AT-A-TIME IS HIGHLY RECOMMENDED**, since those changes are broken out to separate commits. Fixes #53672 Fixes #56216
./src/VisualStudio/Core/Def/Implementation/UnusedReferences/Dialog/UnusedReferencesTableProvider.DataSource.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.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.UnusedReferences; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog { internal partial class UnusedReferencesTableProvider { internal class UnusedReferencesDataSource : ITableDataSource { public const string Name = nameof(UnusedReferencesDataSource); public string SourceTypeIdentifier => Name; public string Identifier => Name; public string? DisplayName => null; private ImmutableList<SinkManager> _managers = ImmutableList<SinkManager>.Empty; private ImmutableArray<UnusedReferencesEntry> _currentEntries = ImmutableArray<UnusedReferencesEntry>.Empty; public IDisposable Subscribe(ITableDataSink sink) { return new SinkManager(this, sink); } public void AddTableData(Solution solution, string projectFilePath, ImmutableArray<ReferenceUpdate> referenceUpdates) { var solutionName = Path.GetFileName(solution.FilePath); var project = solution.Projects.First(project => projectFilePath.Equals(project.FilePath, StringComparison.OrdinalIgnoreCase)); var entries = referenceUpdates .Select(update => new UnusedReferencesEntry(solutionName, project.Name, project.Language, update)) .ToImmutableArray(); foreach (var manager in _managers) { manager.Sink.AddEntries(entries); } _currentEntries = _currentEntries.AddRange(entries); } public void RemoveAllTableData() { foreach (var manager in _managers) { manager.Sink.RemoveAllEntries(); } _currentEntries = ImmutableArray<UnusedReferencesEntry>.Empty; } internal void AddSinkManager(SinkManager manager) { _managers = _managers.Add(manager); manager.Sink.AddEntries(_currentEntries); } internal void RemoveSinkManager(SinkManager manager) { _managers = _managers.Remove(manager); } internal sealed class SinkManager : IDisposable { internal readonly UnusedReferencesDataSource UnusedReferencesDataSource; internal readonly ITableDataSink Sink; internal SinkManager(UnusedReferencesDataSource unusedReferencesDataSource, ITableDataSink sink) { UnusedReferencesDataSource = unusedReferencesDataSource; Sink = sink; UnusedReferencesDataSource.AddSinkManager(this); } public void Dispose() { UnusedReferencesDataSource.RemoveSinkManager(this); } } internal class UnusedReferencesEntry : ITableEntry { public string SolutionName { get; } public string ProjectName { get; } public string Language { get; } public ReferenceUpdate ReferenceUpdate { get; } public object Identity => ReferenceUpdate; public UnusedReferencesEntry(string solutionName, string projectName, string language, ReferenceUpdate referenceUpdate) { SolutionName = solutionName; ProjectName = projectName; Language = language; ReferenceUpdate = referenceUpdate; } public bool TryGetValue(string keyName, out object? content) { content = null; switch (keyName) { case UnusedReferencesTableKeyNames.SolutionName: content = SolutionName; break; case UnusedReferencesTableKeyNames.ProjectName: content = ProjectName; break; case UnusedReferencesTableKeyNames.Language: content = Language; break; case UnusedReferencesTableKeyNames.ReferenceType: content = ReferenceUpdate.ReferenceInfo.ReferenceType; break; case UnusedReferencesTableKeyNames.ReferenceName: // For Project and Assembly references, use the file name instead of overwhelming the user with the full path. content = ReferenceUpdate.ReferenceInfo.ReferenceType != ReferenceType.Package ? Path.GetFileName(ReferenceUpdate.ReferenceInfo.ItemSpecification) : ReferenceUpdate.ReferenceInfo.ItemSpecification; break; case UnusedReferencesTableKeyNames.UpdateAction: content = ReferenceUpdate.Action; break; } return content != null; } public bool CanSetValue(string keyName) { return keyName == UnusedReferencesTableKeyNames.UpdateAction; } public bool TrySetValue(string keyName, object content) { if (keyName != UnusedReferencesTableKeyNames.UpdateAction || content is not UpdateAction action) { return false; } ReferenceUpdate.Action = action; return 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.Collections.Immutable; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.UnusedReferences; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog { internal partial class UnusedReferencesTableProvider { internal class UnusedReferencesDataSource : ITableDataSource { public const string Name = nameof(UnusedReferencesDataSource); public string SourceTypeIdentifier => Name; public string Identifier => Name; public string? DisplayName => null; private ImmutableList<SinkManager> _managers = ImmutableList<SinkManager>.Empty; private ImmutableArray<UnusedReferencesEntry> _currentEntries = ImmutableArray<UnusedReferencesEntry>.Empty; public IDisposable Subscribe(ITableDataSink sink) { return new SinkManager(this, sink); } public void AddTableData(Solution solution, string projectFilePath, ImmutableArray<ReferenceUpdate> referenceUpdates) { var solutionName = Path.GetFileName(solution.FilePath); var project = solution.Projects.First(project => projectFilePath.Equals(project.FilePath, StringComparison.OrdinalIgnoreCase)); var entries = referenceUpdates .Select(update => new UnusedReferencesEntry(solutionName, project.Name, project.Language, update)) .ToImmutableArray(); foreach (var manager in _managers) { manager.Sink.AddEntries(entries); } _currentEntries = _currentEntries.AddRange(entries); } public void RemoveAllTableData() { foreach (var manager in _managers) { manager.Sink.RemoveAllEntries(); } _currentEntries = ImmutableArray<UnusedReferencesEntry>.Empty; } internal void AddSinkManager(SinkManager manager) { _managers = _managers.Add(manager); manager.Sink.AddEntries(_currentEntries); } internal void RemoveSinkManager(SinkManager manager) { _managers = _managers.Remove(manager); } internal sealed class SinkManager : IDisposable { internal readonly UnusedReferencesDataSource UnusedReferencesDataSource; internal readonly ITableDataSink Sink; internal SinkManager(UnusedReferencesDataSource unusedReferencesDataSource, ITableDataSink sink) { UnusedReferencesDataSource = unusedReferencesDataSource; Sink = sink; UnusedReferencesDataSource.AddSinkManager(this); } public void Dispose() { UnusedReferencesDataSource.RemoveSinkManager(this); } } internal class UnusedReferencesEntry : ITableEntry { public string SolutionName { get; } public string ProjectName { get; } public string Language { get; } public ReferenceUpdate ReferenceUpdate { get; } public object Identity => ReferenceUpdate; public UnusedReferencesEntry(string solutionName, string projectName, string language, ReferenceUpdate referenceUpdate) { SolutionName = solutionName; ProjectName = projectName; Language = language; ReferenceUpdate = referenceUpdate; } public bool TryGetValue(string keyName, out object? content) { content = null; switch (keyName) { case UnusedReferencesTableKeyNames.SolutionName: content = SolutionName; break; case UnusedReferencesTableKeyNames.ProjectName: content = ProjectName; break; case UnusedReferencesTableKeyNames.Language: content = Language; break; case UnusedReferencesTableKeyNames.ReferenceType: content = ReferenceUpdate.ReferenceInfo.ReferenceType; break; case UnusedReferencesTableKeyNames.ReferenceName: // For Project and Assembly references, use the file name instead of overwhelming the user with the full path. content = ReferenceUpdate.ReferenceInfo.ReferenceType != ReferenceType.Package ? Path.GetFileName(ReferenceUpdate.ReferenceInfo.ItemSpecification) : ReferenceUpdate.ReferenceInfo.ItemSpecification; break; case UnusedReferencesTableKeyNames.UpdateAction: content = ReferenceUpdate.Action; break; } return content != null; } public bool CanSetValue(string keyName) { return keyName == UnusedReferencesTableKeyNames.UpdateAction; } public bool TrySetValue(string keyName, object content) { if (keyName != UnusedReferencesTableKeyNames.UpdateAction || content is not UpdateAction action) { return false; } ReferenceUpdate.Action = action; return true; } } } } }
-1