repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/Portable/Collections/ArrayElement.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis
{
[DebuggerDisplay("{Value,nq}")]
internal struct ArrayElement<T>
{
internal T Value;
public static implicit operator T(ArrayElement<T> element)
{
return element.Value;
}
//NOTE: there is no opposite conversion operator T -> ArrayElement<T>
//
// that is because it is preferred to update array elements in-place
// "elements[i].Value = v" results in much better code than "elements[i] = (ArrayElement<T>)v"
//
// The reason is that x86 ABI requires that structs must be returned in
// a return buffer even if they can fit in a register like this one.
// Also since struct contains a reference, the write to the buffer is done with a checked GC barrier
// as JIT does not know if the write goes to a stack or a heap location.
// Assigning to Value directly easily avoids all this redundancy.
[return: NotNullIfNotNull(parameterName: "items")]
public static ArrayElement<T>[]? MakeElementArray(T[]? items)
{
if (items == null)
{
return null;
}
var array = new ArrayElement<T>[items.Length];
for (int i = 0; i < items.Length; i++)
{
array[i].Value = items[i];
}
return array;
}
[return: NotNullIfNotNull(parameterName: "items")]
public static T[]? MakeArray(ArrayElement<T>[]? items)
{
if (items == null)
{
return null;
}
var array = new T[items.Length];
for (int i = 0; i < items.Length; i++)
{
array[i] = items[i].Value;
}
return array;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis
{
[DebuggerDisplay("{Value,nq}")]
internal struct ArrayElement<T>
{
internal T Value;
public static implicit operator T(ArrayElement<T> element)
{
return element.Value;
}
//NOTE: there is no opposite conversion operator T -> ArrayElement<T>
//
// that is because it is preferred to update array elements in-place
// "elements[i].Value = v" results in much better code than "elements[i] = (ArrayElement<T>)v"
//
// The reason is that x86 ABI requires that structs must be returned in
// a return buffer even if they can fit in a register like this one.
// Also since struct contains a reference, the write to the buffer is done with a checked GC barrier
// as JIT does not know if the write goes to a stack or a heap location.
// Assigning to Value directly easily avoids all this redundancy.
[return: NotNullIfNotNull(parameterName: "items")]
public static ArrayElement<T>[]? MakeElementArray(T[]? items)
{
if (items == null)
{
return null;
}
var array = new ArrayElement<T>[items.Length];
for (int i = 0; i < items.Length; i++)
{
array[i].Value = items[i];
}
return array;
}
[return: NotNullIfNotNull(parameterName: "items")]
public static T[]? MakeArray(ArrayElement<T>[]? items)
{
if (items == null)
{
return null;
}
var array = new T[items.Length];
for (int i = 0; i < items.Length; i++)
{
array[i] = items[i].Value;
}
return array;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/Core/Impl/Options/AbstractRadioButtonViewModel.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.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
internal abstract class AbstractRadioButtonViewModel : AbstractNotifyPropertyChanged
{
private readonly AbstractOptionPreviewViewModel _info;
internal readonly string Preview;
private bool _isChecked;
public string Description { get; }
public string GroupName { get; }
public bool IsChecked
{
get
{
return _isChecked;
}
set
{
SetProperty(ref _isChecked, value);
if (_isChecked)
{
SetOptionAndUpdatePreview(_info, Preview);
}
}
}
public AbstractRadioButtonViewModel(string description, string preview, AbstractOptionPreviewViewModel info, bool isChecked, string group)
{
Description = description;
this.Preview = preview;
_info = info;
this.GroupName = group;
SetProperty(ref _isChecked, isChecked);
}
internal abstract void SetOptionAndUpdatePreview(AbstractOptionPreviewViewModel info, string preview);
}
}
| // Licensed to the .NET Foundation under one or more 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.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
internal abstract class AbstractRadioButtonViewModel : AbstractNotifyPropertyChanged
{
private readonly AbstractOptionPreviewViewModel _info;
internal readonly string Preview;
private bool _isChecked;
public string Description { get; }
public string GroupName { get; }
public bool IsChecked
{
get
{
return _isChecked;
}
set
{
SetProperty(ref _isChecked, value);
if (_isChecked)
{
SetOptionAndUpdatePreview(_info, Preview);
}
}
}
public AbstractRadioButtonViewModel(string description, string preview, AbstractOptionPreviewViewModel info, bool isChecked, string group)
{
Description = description;
this.Preview = preview;
_info = info;
this.GroupName = group;
SetProperty(ref _isChecked, isChecked);
}
internal abstract void SetOptionAndUpdatePreview(AbstractOptionPreviewViewModel info, string preview);
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Portable/Symbols/NonMissingAssemblySymbol.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.Collections.Concurrent
Imports System.Collections.ObjectModel
Imports System.Reflection
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A <see cref="NonMissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents
''' an assembly that is not missing, i.e. the "real" thing.
''' </summary>
Friend MustInherit Class NonMissingAssemblySymbol
Inherits AssemblySymbol
''' <summary>
''' This is a cache similar to the one used by MetaImport::GetTypeByName
''' in native compiler. The difference is that native compiler pre-populates
''' the cache when it loads types. Here we are populating the cache only
''' with things we looked for, so that next time we are looking for the same
''' thing, the lookup is fast. This cache also takes care of TypeForwarders.
''' Gives about 8% win on subsequent lookups in some scenarios.
''' </summary>
''' <remarks></remarks>
Private ReadOnly _emittedNameToTypeMap As New ConcurrentDictionary(Of MetadataTypeName.Key, NamedTypeSymbol)()
''' <summary>
''' The global namespace symbol. Lazily populated on first access.
''' </summary>
Private _lazyGlobalNamespace As NamespaceSymbol
''' <summary>
''' Does this symbol represent a missing assembly.
''' </summary>
Friend NotOverridable Overrides ReadOnly Property IsMissing As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Gets the merged root namespace that contains all namespaces and types defined in the modules
''' of this assembly. If there is just one module in this assembly, this property just returns the
''' GlobalNamespace of that module.
''' </summary>
Public NotOverridable Overrides ReadOnly Property GlobalNamespace As NamespaceSymbol
Get
If _lazyGlobalNamespace Is Nothing Then
Interlocked.CompareExchange(_lazyGlobalNamespace, MergedNamespaceSymbol.CreateGlobalNamespace(Me), Nothing)
End If
Return _lazyGlobalNamespace
End Get
End Property
''' <summary>
''' Lookup a top level type referenced from metadata, names should be
''' compared case-sensitively. Detect cycles during lookup.
''' </summary>
''' <param name="emittedName">
''' Full type name, possibly with generic name mangling.
''' </param>
''' <param name="visitedAssemblies">
''' List of assemblies lookup has already visited (since type forwarding can introduce cycles).
''' </param>
''' <param name="digThroughForwardedTypes">
''' Take forwarded types into account.
''' </param>
Friend NotOverridable Overrides Function LookupTopLevelMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), digThroughForwardedTypes As Boolean) As NamedTypeSymbol
Dim result As NamedTypeSymbol = Nothing
' This is a cache similar to the one used by MetaImport::GetTypeByName
' in native compiler. The difference is that native compiler pre-populates
' the cache when it loads types. Here we are populating the cache only
' with things we looked for, so that next time we are looking for the same
' thing, the lookup is fast. This cache also takes care of TypeForwarders.
' Gives about 8% win on subsequent lookups in some scenarios.
'
' CONSIDER !!!
'
' However, it is questionable how often subsequent lookup by name is going to happen.
' Currently it doesn't happen for TypeDef tokens at all, for TypeRef tokens, the lookup by name
' is done once and the result is cached. So, multiple lookups by name for the same type
' are going to happen only in these cases:
' 1) Resolving GetType() in attribute application, type is encoded by name.
' 2) TypeRef token isn't reused within the same module, i.e. multiple TypeRefs point to the same type.
' 3) Different Module refers to the same type, lookup once per Module (with exception of #2).
' 4) Multitargeting - retargeting the type to a different version of assembly
result = LookupTopLevelMetadataTypeInCache(emittedName)
If result IsNot Nothing Then
' We only cache result equivalent to digging through type forwarders, which
' might produce a forwarder specific ErrorTypeSymbol. We don't want to
' return that error symbol, unless digThroughForwardedTypes Is true.
If digThroughForwardedTypes OrElse (Not result.IsErrorType() AndAlso result.ContainingAssembly Is Me) Then
Return result
End If
' According to the cache, the type wasn't found, or isn't declared in this assembly (forwarded).
Return New MissingMetadataTypeSymbol.TopLevel(Me.Modules(0), emittedName)
End If
' Now we will look for the type in each module of the assembly and pick the
' first type we find, this is what native VB compiler does.
Dim modules = Me.Modules
Dim count As Integer = modules.Length
Dim i As Integer = 0
result = modules(i).LookupTopLevelMetadataType(emittedName)
If TypeOf result Is MissingMetadataTypeSymbol Then
For i = 1 To count - 1 Step 1
Dim newResult = modules(i).LookupTopLevelMetadataType(emittedName)
' Hold on to the first missing type result, unless we found the type.
If Not (TypeOf newResult Is MissingMetadataTypeSymbol) Then
result = newResult
Exit For
End If
Next
End If
Dim foundMatchInThisAssembly As Boolean = (i < count)
Debug.Assert(Not foundMatchInThisAssembly OrElse result.ContainingAssembly Is Me)
If Not foundMatchInThisAssembly AndAlso digThroughForwardedTypes Then
' We didn't find the type
Debug.Assert(TypeOf result Is MissingMetadataTypeSymbol)
Dim forwarded As NamedTypeSymbol = TryLookupForwardedMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, ignoreCase:=False)
If forwarded IsNot Nothing Then
result = forwarded
End If
End If
Debug.Assert(result IsNot Nothing)
' Add result of the lookup into the cache
If digThroughForwardedTypes OrElse foundMatchInThisAssembly Then
CacheTopLevelMetadataType(emittedName, result)
End If
Return result
End Function
Friend MustOverride Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol
''' <summary>
''' For test purposes only.
''' </summary>
Friend Function CachedTypeByEmittedName(emittedname As String) As NamedTypeSymbol
Dim mdName = MetadataTypeName.FromFullName(emittedname)
Return _emittedNameToTypeMap(mdName.ToKey())
End Function
''' <summary>
''' For test purposes only.
''' </summary>
Friend ReadOnly Property EmittedNameToTypeMapCount As Integer
Get
Return _emittedNameToTypeMap.Count
End Get
End Property
Private Function LookupTopLevelMetadataTypeInCache(
ByRef emittedName As MetadataTypeName
) As NamedTypeSymbol
Dim result As NamedTypeSymbol = Nothing
If Me._emittedNameToTypeMap.TryGetValue(emittedName.ToKey(), result) Then
Return result
End If
Return Nothing
End Function
Private Sub CacheTopLevelMetadataType(
ByRef emittedName As MetadataTypeName,
result As NamedTypeSymbol
)
Dim result1 As NamedTypeSymbol = Nothing
result1 = Me._emittedNameToTypeMap.GetOrAdd(emittedName.ToKey(), result)
Debug.Assert(result1.Equals(result)) ' object identity may differ in error cases
End Sub
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
Imports System.Collections.Concurrent
Imports System.Collections.ObjectModel
Imports System.Reflection
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A <see cref="NonMissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents
''' an assembly that is not missing, i.e. the "real" thing.
''' </summary>
Friend MustInherit Class NonMissingAssemblySymbol
Inherits AssemblySymbol
''' <summary>
''' This is a cache similar to the one used by MetaImport::GetTypeByName
''' in native compiler. The difference is that native compiler pre-populates
''' the cache when it loads types. Here we are populating the cache only
''' with things we looked for, so that next time we are looking for the same
''' thing, the lookup is fast. This cache also takes care of TypeForwarders.
''' Gives about 8% win on subsequent lookups in some scenarios.
''' </summary>
''' <remarks></remarks>
Private ReadOnly _emittedNameToTypeMap As New ConcurrentDictionary(Of MetadataTypeName.Key, NamedTypeSymbol)()
''' <summary>
''' The global namespace symbol. Lazily populated on first access.
''' </summary>
Private _lazyGlobalNamespace As NamespaceSymbol
''' <summary>
''' Does this symbol represent a missing assembly.
''' </summary>
Friend NotOverridable Overrides ReadOnly Property IsMissing As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Gets the merged root namespace that contains all namespaces and types defined in the modules
''' of this assembly. If there is just one module in this assembly, this property just returns the
''' GlobalNamespace of that module.
''' </summary>
Public NotOverridable Overrides ReadOnly Property GlobalNamespace As NamespaceSymbol
Get
If _lazyGlobalNamespace Is Nothing Then
Interlocked.CompareExchange(_lazyGlobalNamespace, MergedNamespaceSymbol.CreateGlobalNamespace(Me), Nothing)
End If
Return _lazyGlobalNamespace
End Get
End Property
''' <summary>
''' Lookup a top level type referenced from metadata, names should be
''' compared case-sensitively. Detect cycles during lookup.
''' </summary>
''' <param name="emittedName">
''' Full type name, possibly with generic name mangling.
''' </param>
''' <param name="visitedAssemblies">
''' List of assemblies lookup has already visited (since type forwarding can introduce cycles).
''' </param>
''' <param name="digThroughForwardedTypes">
''' Take forwarded types into account.
''' </param>
Friend NotOverridable Overrides Function LookupTopLevelMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), digThroughForwardedTypes As Boolean) As NamedTypeSymbol
Dim result As NamedTypeSymbol = Nothing
' This is a cache similar to the one used by MetaImport::GetTypeByName
' in native compiler. The difference is that native compiler pre-populates
' the cache when it loads types. Here we are populating the cache only
' with things we looked for, so that next time we are looking for the same
' thing, the lookup is fast. This cache also takes care of TypeForwarders.
' Gives about 8% win on subsequent lookups in some scenarios.
'
' CONSIDER !!!
'
' However, it is questionable how often subsequent lookup by name is going to happen.
' Currently it doesn't happen for TypeDef tokens at all, for TypeRef tokens, the lookup by name
' is done once and the result is cached. So, multiple lookups by name for the same type
' are going to happen only in these cases:
' 1) Resolving GetType() in attribute application, type is encoded by name.
' 2) TypeRef token isn't reused within the same module, i.e. multiple TypeRefs point to the same type.
' 3) Different Module refers to the same type, lookup once per Module (with exception of #2).
' 4) Multitargeting - retargeting the type to a different version of assembly
result = LookupTopLevelMetadataTypeInCache(emittedName)
If result IsNot Nothing Then
' We only cache result equivalent to digging through type forwarders, which
' might produce a forwarder specific ErrorTypeSymbol. We don't want to
' return that error symbol, unless digThroughForwardedTypes Is true.
If digThroughForwardedTypes OrElse (Not result.IsErrorType() AndAlso result.ContainingAssembly Is Me) Then
Return result
End If
' According to the cache, the type wasn't found, or isn't declared in this assembly (forwarded).
Return New MissingMetadataTypeSymbol.TopLevel(Me.Modules(0), emittedName)
End If
' Now we will look for the type in each module of the assembly and pick the
' first type we find, this is what native VB compiler does.
Dim modules = Me.Modules
Dim count As Integer = modules.Length
Dim i As Integer = 0
result = modules(i).LookupTopLevelMetadataType(emittedName)
If TypeOf result Is MissingMetadataTypeSymbol Then
For i = 1 To count - 1 Step 1
Dim newResult = modules(i).LookupTopLevelMetadataType(emittedName)
' Hold on to the first missing type result, unless we found the type.
If Not (TypeOf newResult Is MissingMetadataTypeSymbol) Then
result = newResult
Exit For
End If
Next
End If
Dim foundMatchInThisAssembly As Boolean = (i < count)
Debug.Assert(Not foundMatchInThisAssembly OrElse result.ContainingAssembly Is Me)
If Not foundMatchInThisAssembly AndAlso digThroughForwardedTypes Then
' We didn't find the type
Debug.Assert(TypeOf result Is MissingMetadataTypeSymbol)
Dim forwarded As NamedTypeSymbol = TryLookupForwardedMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, ignoreCase:=False)
If forwarded IsNot Nothing Then
result = forwarded
End If
End If
Debug.Assert(result IsNot Nothing)
' Add result of the lookup into the cache
If digThroughForwardedTypes OrElse foundMatchInThisAssembly Then
CacheTopLevelMetadataType(emittedName, result)
End If
Return result
End Function
Friend MustOverride Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol
''' <summary>
''' For test purposes only.
''' </summary>
Friend Function CachedTypeByEmittedName(emittedname As String) As NamedTypeSymbol
Dim mdName = MetadataTypeName.FromFullName(emittedname)
Return _emittedNameToTypeMap(mdName.ToKey())
End Function
''' <summary>
''' For test purposes only.
''' </summary>
Friend ReadOnly Property EmittedNameToTypeMapCount As Integer
Get
Return _emittedNameToTypeMap.Count
End Get
End Property
Private Function LookupTopLevelMetadataTypeInCache(
ByRef emittedName As MetadataTypeName
) As NamedTypeSymbol
Dim result As NamedTypeSymbol = Nothing
If Me._emittedNameToTypeMap.TryGetValue(emittedName.ToKey(), result) Then
Return result
End If
Return Nothing
End Function
Private Sub CacheTopLevelMetadataType(
ByRef emittedName As MetadataTypeName,
result As NamedTypeSymbol
)
Dim result1 As NamedTypeSymbol = Nothing
result1 = Me._emittedNameToTypeMap.GetOrAdd(emittedName.ToKey(), result)
Debug.Assert(result1.Equals(result)) ' object identity may differ in error cases
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./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 | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/Core.Wpf/SignatureHelp/Presentation/SignatureHelpPresenter.SignatureHelpSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Language.Intellisense;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation
{
internal partial class SignatureHelpPresenter
{
private class SignatureHelpSource : ForegroundThreadAffinitizedObject, ISignatureHelpSource
{
public SignatureHelpSource(IThreadingContext threadingContext)
: base(threadingContext)
{
}
public void AugmentSignatureHelpSession(ISignatureHelpSession session, IList<ISignature> signatures)
{
AssertIsForeground();
if (!session.Properties.TryGetProperty<SignatureHelpPresenterSession>(s_augmentSessionKey, out var presenterSession))
{
return;
}
session.Properties.RemoveProperty(s_augmentSessionKey);
presenterSession.AugmentSignatureHelpSession(signatures);
}
public ISignature GetBestMatch(ISignatureHelpSession session)
{
AssertIsForeground();
return session.SelectedSignature;
}
public void 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.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Language.Intellisense;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation
{
internal partial class SignatureHelpPresenter
{
private class SignatureHelpSource : ForegroundThreadAffinitizedObject, ISignatureHelpSource
{
public SignatureHelpSource(IThreadingContext threadingContext)
: base(threadingContext)
{
}
public void AugmentSignatureHelpSession(ISignatureHelpSession session, IList<ISignature> signatures)
{
AssertIsForeground();
if (!session.Properties.TryGetProperty<SignatureHelpPresenterSession>(s_augmentSessionKey, out var presenterSession))
{
return;
}
session.Properties.RemoveProperty(s_augmentSessionKey);
presenterSession.AugmentSignatureHelpSession(signatures);
}
public ISignature GetBestMatch(ISignatureHelpSession session)
{
AssertIsForeground();
return session.SelectedSignature;
}
public void Dispose()
{
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/Core/Implementation/CommentSelection/ToggleBlockCommentCommandHandler.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.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommentSelection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection
{
[Export(typeof(ICommandHandler))]
[VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)]
[VisualStudio.Utilities.Name(PredefinedCommandHandlerNames.ToggleBlockComment)]
internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ToggleBlockCommentCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService,
ITextStructureNavigatorSelectorService navigatorSelectorService)
: base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService)
{
}
/// <summary>
/// Gets block comments by parsing the text for comment markers.
/// </summary>
protected override Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot,
TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken)
{
var allText = snapshot.AsText();
var commentedSpans = ArrayBuilder<TextSpan>.GetInstance();
var openIdx = 0;
while ((openIdx = allText.IndexOf(commentInfo.BlockCommentStartString, openIdx, caseSensitive: true)) >= 0)
{
// Retrieve the first closing marker located after the open index.
var closeIdx = allText.IndexOf(commentInfo.BlockCommentEndString, openIdx + commentInfo.BlockCommentStartString.Length, caseSensitive: true);
// If an open marker is found without a close marker, it's an unclosed comment.
if (closeIdx < 0)
{
closeIdx = allText.Length - commentInfo.BlockCommentEndString.Length;
}
var blockCommentSpan = new TextSpan(openIdx, closeIdx + commentInfo.BlockCommentEndString.Length - openIdx);
commentedSpans.Add(blockCommentSpan);
openIdx = closeIdx;
}
return Task.FromResult(commentedSpans.ToImmutableAndFree());
}
}
}
| // Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommentSelection;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection
{
[Export(typeof(ICommandHandler))]
[VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)]
[VisualStudio.Utilities.Name(PredefinedCommandHandlerNames.ToggleBlockComment)]
internal class ToggleBlockCommentCommandHandler : AbstractToggleBlockCommentBase
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ToggleBlockCommentCommandHandler(
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService,
ITextStructureNavigatorSelectorService navigatorSelectorService)
: base(undoHistoryRegistry, editorOperationsFactoryService, navigatorSelectorService)
{
}
/// <summary>
/// Gets block comments by parsing the text for comment markers.
/// </summary>
protected override Task<ImmutableArray<TextSpan>> GetBlockCommentsInDocumentAsync(Document document, ITextSnapshot snapshot,
TextSpan linesContainingSelections, CommentSelectionInfo commentInfo, CancellationToken cancellationToken)
{
var allText = snapshot.AsText();
var commentedSpans = ArrayBuilder<TextSpan>.GetInstance();
var openIdx = 0;
while ((openIdx = allText.IndexOf(commentInfo.BlockCommentStartString, openIdx, caseSensitive: true)) >= 0)
{
// Retrieve the first closing marker located after the open index.
var closeIdx = allText.IndexOf(commentInfo.BlockCommentEndString, openIdx + commentInfo.BlockCommentStartString.Length, caseSensitive: true);
// If an open marker is found without a close marker, it's an unclosed comment.
if (closeIdx < 0)
{
closeIdx = allText.Length - commentInfo.BlockCommentEndString.Length;
}
var blockCommentSpan = new TextSpan(openIdx, closeIdx + commentInfo.BlockCommentEndString.Length - openIdx);
commentedSpans.Add(blockCommentSpan);
openIdx = closeIdx;
}
return Task.FromResult(commentedSpans.ToImmutableAndFree());
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/CSharp/Portable/Symbols/TypeSymbol.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.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
#pragma warning disable CS0660
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A TypeSymbol is a base class for all the symbols that represent a type
/// in C#.
/// </summary>
internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal
{
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// 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.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages.
internal const string ImplicitTypeName = "<invalid-global-code>";
// InterfaceInfo for a common case of a type not implementing anything directly or indirectly.
private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo();
private ImmutableHashSet<Symbol> _lazyAbstractMembers;
private InterfaceInfo _lazyInterfaceInfo;
private class InterfaceInfo
{
// all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively
internal ImmutableArray<NamedTypeSymbol> allInterfaces;
/// <summary>
/// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/>
/// </summary>
internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces;
internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces =
new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature);
// Key is implemented member (method, property, or event), value is implementing member (from the
// perspective of this type). Don't allocate until someone needs it.
private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap;
public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap
{
get
{
var map = _implementationForInterfaceMemberMap;
if (map != null)
{
return map;
}
// PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates.
map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything);
return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map;
}
}
/// <summary>
/// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>,
/// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of
/// an error).
/// </summary>
internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap;
#nullable enable
internal ImmutableDictionary<MethodSymbol, MethodSymbol>? synthesizedMethodImplMap;
#nullable disable
internal bool IsDefaultValue()
{
return allInterfaces.IsDefault &&
interfacesAndTheirBaseInterfaces == null &&
_implementationForInterfaceMemberMap == null &&
explicitInterfaceImplementationMap == null &&
synthesizedMethodImplMap == null;
}
}
private InterfaceInfo GetInterfaceInfo()
{
var info = _lazyInterfaceInfo;
if (info != null)
{
Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified");
return info;
}
for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics)
{
var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics();
if (!interfaces.IsEmpty)
{
// it looks like we or one of our bases implements something.
info = new InterfaceInfo();
// NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness,
// we just do not want to override an existing info that could be partially filled.
return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info;
}
}
// if we have got here it means neither we nor our bases implement anything
_lazyInterfaceInfo = info = s_noInterfaces;
return info;
}
/// <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 TypeSymbol OriginalDefinition
{
get
{
return OriginalTypeSymbolDefinition;
}
}
protected virtual TypeSymbol OriginalTypeSymbolDefinition
{
get
{
return this;
}
}
protected sealed override Symbol OriginalSymbolDefinition
{
get
{
return this.OriginalTypeSymbolDefinition;
}
}
/// <summary>
/// Gets the BaseType of this type. If the base type could not be determined, then
/// an instance of ErrorType is returned. If this kind of type does not have a base type
/// (for example, interfaces), null is returned. Also the special class System.Object
/// always has a BaseType of null.
/// </summary>
internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; }
internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var result = BaseTypeNoUseSiteDiagnostics;
if ((object)result != null)
{
result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo);
}
return result;
}
internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var result = BaseTypeNoUseSiteDiagnostics;
if ((object)result != null)
{
result = result.OriginalDefinition;
result.AddUseSiteInfo(ref useSiteInfo);
}
return result;
}
/// <summary>
/// Gets the set of interfaces that this type directly implements. This set does not include
/// interfaces that are base interfaces of directly implemented interfaces.
/// </summary>
internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null);
/// <summary>
/// The list of all interfaces of which this type is a declared subtype, excluding this type
/// itself. This includes all declared base interfaces, all declared base interfaces of base
/// types, and all declared base interfaces of those results (recursively). Each result
/// appears exactly once in the list. This list is topologically sorted by the inheritance
/// relationship: if interface type A extends interface type B, then A precedes B in the
/// list. This is not quite the same as "all interfaces of which this type is a proper
/// subtype" because it does not take into account variance: AllInterfaces for
/// IEnumerable<string> will not include IEnumerable<object>
/// </summary>
internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics
{
get
{
return GetAllInterfaces();
}
}
internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var result = AllInterfacesNoUseSiteDiagnostics;
// Since bases affect content of AllInterfaces set, we need to make sure they all are good.
var current = this;
do
{
current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
}
while ((object)current != null);
foreach (var iface in result)
{
iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo);
}
return result;
}
/// <summary>
/// If this is a type parameter returns its effective base class, otherwise returns this type.
/// </summary>
internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics
{
get
{
return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this;
}
}
internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo) : this;
}
/// <summary>
/// Returns true if this type derives from a given type.
/// </summary>
internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert((object)type != null);
Debug.Assert(!type.IsTypeParameter());
if ((object)this == (object)type)
{
return false;
}
var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
while ((object)t != null)
{
if (type.Equals(t, comparison))
{
return true;
}
t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
}
return false;
}
/// <summary>
/// Returns true if this type is equal or derives from a given type.
/// </summary>
internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteInfo);
}
/// <summary>
/// Determines if this type symbol represent the same type as another, according to the language
/// semantics.
/// </summary>
/// <param name="t2">The other type.</param>
/// <param name="compareKind">
/// What kind of comparison to use?
/// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences.
/// </param>
/// <returns>True if the types are equivalent.</returns>
internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind)
{
return ReferenceEquals(this, t2);
}
public sealed override bool Equals(Symbol other, TypeCompareKind compareKind)
{
var t2 = other as TypeSymbol;
if (t2 is null)
{
return false;
}
return this.Equals(t2, compareKind);
}
/// <summary>
/// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces()
{
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
if (info.allInterfaces.IsDefault)
{
ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces());
}
return info.allInterfaces;
}
/// Produce all implemented interfaces in topologically sorted order. We use
/// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely
/// long dependency cycles removed. Consequently, it is possible (and we do) use the
/// simplest version of Tarjan's topological sorting algorithm.
protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces()
{
var result = ArrayBuilder<NamedTypeSymbol>.GetInstance();
var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything);
for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics)
{
var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics();
for (int i = interfaces.Length - 1; i >= 0; i--)
{
addAllInterfaces(interfaces[i], visited, result);
}
}
result.ReverseContents();
return result.ToImmutableAndFree();
static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result)
{
if (visited.Add(@interface))
{
ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics();
for (int i = baseInterfaces.Length - 1; i >= 0; i--)
{
var baseInterface = baseInterfaces[i];
addAllInterfaces(baseInterface, visited, result);
}
result.Add(@interface);
}
}
}
/// <summary>
/// Gets the set of interfaces that this type directly implements, plus the base interfaces
/// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>,
/// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules.
/// </summary>
/// <remarks>
/// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider
/// alternative approaches (recompute every time, cache on the side, only store on some types,
/// etc).
/// </remarks>
internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics
{
get
{
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty);
return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces;
}
if (info.interfacesAndTheirBaseInterfaces == null)
{
Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null);
}
return info.interfacesAndTheirBaseInterfaces;
}
}
internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;
foreach (var iface in result.Keys)
{
iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo);
}
return result;
}
// Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on
// AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces
// indirectly.
private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces)
{
var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything);
foreach (var @interface in declaredInterfaces)
{
if (resultBuilder.Add(@interface, @interface))
{
foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics)
{
resultBuilder.Add(baseInterface, baseInterface);
}
}
}
return resultBuilder;
}
/// <summary>
/// Returns the corresponding symbol in this type or a base type that implements
/// interfaceMember (either implicitly or explicitly), or null if no such symbol exists
/// (which might be either because this type doesn't implement the container of
/// interfaceMember, or this type doesn't supply a member that successfully implements
/// interfaceMember).
/// </summary>
/// <param name="interfaceMember">
/// Must be a non-null interface property, method, or event.
/// </param>
public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember)
{
if ((object)interfaceMember == null)
{
throw new ArgumentNullException(nameof(interfaceMember));
}
if (!interfaceMember.IsImplementableInterfaceMember())
{
return null;
}
if (this.IsInterfaceType())
{
if (interfaceMember.IsStatic)
{
return null;
}
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref discardedUseSiteInfo);
}
return FindImplementationForInterfaceMemberInNonInterface(interfaceMember);
}
/// <summary>
/// Returns true if this type is known to be a reference type. It is never the case that
/// IsReferenceType and IsValueType both return true. However, for an unconstrained type
/// parameter, IsReferenceType and IsValueType will both return false.
/// </summary>
public abstract bool IsReferenceType { get; }
/// <summary>
/// Returns true if this type is known to be a value type. It is never the case that
/// IsReferenceType and IsValueType both return true. However, for an unconstrained type
/// parameter, IsReferenceType and IsValueType will both return false.
/// </summary>
public abstract bool IsValueType { get; }
// Only the compiler can create TypeSymbols.
internal TypeSymbol()
{
}
/// <summary>
/// Gets the kind of this type.
/// </summary>
public abstract TypeKind TypeKind { get; }
/// <summary>
/// Gets corresponding special TypeId of this type.
/// </summary>
/// <remarks>
/// Not preserved in types constructed from this one.
/// </remarks>
public virtual SpecialType SpecialType
{
get
{
return SpecialType.None;
}
}
/// <summary>
/// Gets corresponding primitive type code for this type declaration.
/// </summary>
internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode
=> TypeKind switch
{
TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer,
TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer,
_ => SpecialTypes.GetTypeCode(SpecialType)
};
#region Use-Site Diagnostics
/// <summary>
/// Return error code that has highest priority while calculating use site error for this symbol.
/// </summary>
protected override int HighestPriorityUseSiteError
{
get
{
return (int)ErrorCode.ERR_BogusType;
}
}
public sealed override bool HasUnsupportedMetadata
{
get
{
DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo;
return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType;
}
}
internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes);
#endregion
/// <summary>
/// Is this a symbol for an anonymous type (including delegate).
/// </summary>
public virtual bool IsAnonymousType
{
get
{
return false;
}
}
/// <summary>
/// Is this a symbol for a Tuple.
/// </summary>
public virtual bool IsTupleType => false;
/// <summary>
/// True if the type represents a native integer. In C#, the types represented
/// by language keywords 'nint' and 'nuint'.
/// </summary>
internal virtual bool IsNativeIntegerType => false;
/// <summary>
/// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type
/// with the given cardinality.
/// </summary>
internal bool IsTupleTypeOfCardinality(int targetCardinality)
{
if (IsTupleType)
{
return TupleElementTypesWithAnnotations.Length == targetCardinality;
}
return false;
}
/// <summary>
/// If this symbol represents a tuple type, get the types of the tuple's elements.
/// </summary>
public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>);
/// <summary>
/// If this symbol represents a tuple type, get the names of the tuple's elements.
/// </summary>
public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>);
/// <summary>
/// If this symbol represents a tuple type, get the fields for the tuple's elements.
/// Otherwise, returns default.
/// </summary>
public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>);
#nullable enable
/// <summary>
/// Is this type a managed type (false for everything but enum, pointer, and
/// some struct types).
/// </summary>
/// <remarks>
/// See Type::computeManagedType.
/// </remarks>
internal bool IsManagedType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => GetManagedKind(ref useSiteInfo) == ManagedKind.Managed;
internal bool IsManagedTypeNoUseSiteDiagnostics
{
get
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return IsManagedType(ref discardedUseSiteInfo);
}
}
/// <summary>
/// Indicates whether a type is managed or not (i.e. you can take a pointer to it).
/// Contains additional cases to help implement FeatureNotAvailable diagnostics.
/// </summary>
internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo);
internal ManagedKind ManagedKindNoUseSiteDiagnostics
{
get
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return GetManagedKind(ref discardedUseSiteInfo);
}
}
#nullable disable
internal bool NeedsNullableAttribute()
{
return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this);
}
internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms);
internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result);
internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform);
internal TypeSymbol SetUnknownNullabilityForReferenceTypes()
{
return SetNullabilityForReferenceTypes(s_setUnknownNullability);
}
private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability =
(type) => type.SetUnknownNullabilityForReferenceTypes();
/// <summary>
/// Merges features of the type with another type where there is an identity conversion between them.
/// The features to be merged are
/// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable
/// annotations (e.g. in type arguments).
/// </summary>
internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance);
/// <summary>
/// Returns true if the type may contain embedded references
/// </summary>
public abstract bool IsRefLikeType { get; }
/// <summary>
/// Returns true if the type is a readonly struct
/// </summary>
public abstract bool IsReadOnly { get; }
public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format);
}
public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format);
}
public string ToMinimalDisplayString(
SemanticModel semanticModel,
CodeAnalysis.NullableFlowState topLevelNullability,
int position,
SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format);
}
public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(
SemanticModel semanticModel,
CodeAnalysis.NullableFlowState topLevelNullability,
int position,
SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format);
}
#region Interface member checks
/// <summary>
/// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type.
/// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>.
/// </summary>
/// <param name="interfaceMember">Member for which an implementation should be found.</param>
/// <param name="ignoreImplementationInInterfacesIfResultIsNotReady">
/// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented,
/// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can
/// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can
/// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of
/// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of
/// implementations in interfaces and we use that.
/// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not
/// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from
/// the cache is returned.
/// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations
/// in interfaces into account and then cached.
/// This means that:
/// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true.
/// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value.
/// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent
/// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value.
/// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with
/// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface.
/// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call
/// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value.
/// </param>
internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false)
{
Debug.Assert((object)interfaceMember != null);
Debug.Assert(!this.IsInterfaceType());
if (this.IsInterfaceType())
{
return SymbolAndDiagnostics.Empty;
}
var interfaceType = interfaceMember.ContainingType;
if ((object)interfaceType == null || !interfaceType.IsInterface)
{
return SymbolAndDiagnostics.Empty;
}
switch (interfaceMember.Kind)
{
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
return SymbolAndDiagnostics.Empty;
}
// PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd
var map = info.ImplementationForInterfaceMemberMap;
SymbolAndDiagnostics result;
if (map.TryGetValue(interfaceMember, out result))
{
return result;
}
result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady,
out bool implementationInInterfacesMightChangeResult);
Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult);
Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null);
if (!implementationInInterfacesMightChangeResult)
{
map.TryAdd(interfaceMember, result);
}
return result;
default:
return SymbolAndDiagnostics.Empty;
}
}
internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false)
{
return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol;
}
private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult)
{
var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: this.DeclaringCompilation is object);
var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult);
var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree());
return implementingMemberAndDiagnostics;
}
/// <summary>
/// Performs interface mapping (spec 13.4.4).
/// </summary>
/// <remarks>
/// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics.
/// </remarks>
/// <param name="interfaceMember">A non-null implementable member on an interface type.</param>
/// <param name="implementingType">The type implementing the interface property (usually "this").</param>
/// <param name="diagnostics">Bag to which to add diagnostics.</param>
/// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param>
/// <param name="implementationInInterfacesMightChangeResult">
/// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in
/// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise.
/// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any,
/// is guaranteed to be from an interface.
/// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>.
/// </param>
/// <returns>The implementing property or null, if there isn't one.</returns>
private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics,
bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult)
{
Debug.Assert(!implementingType.IsInterfaceType());
Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event);
Debug.Assert(interfaceMember.IsImplementableInterfaceMember());
NamedTypeSymbol interfaceType = interfaceMember.ContainingType;
Debug.Assert((object)interfaceType != null && interfaceType.IsInterface);
bool seenTypeDeclaringInterface = false;
// NOTE: In other areas of the compiler, we check whether the member is from a specific compilation.
// We could do the same thing here, but that would mean that callers of the public API would have
// to pass in a Compilation object when asking about interface implementation. This extra cost eliminates
// the small benefit of getting identical answers from "imported" symbols, regardless of whether they
// are imported as source or metadata symbols.
//
// ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors
// disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous
// overrides, which typically arise through combinations of ref/out and generics.) In incorrect code,
// the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type),
// but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata.
//
// NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these
// APIs on symbols from other compilations.
bool implementingTypeIsFromSomeCompilation = false;
Symbol implicitImpl = null;
Symbol closestMismatch = null;
bool canBeImplementedImplicitlyInCSharp9 = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor();
TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false
bool implementingTypeImplementsInterface = false;
CSharpCompilation compilation = implementingType.DeclaringCompilation;
var useSiteInfo = compilation is object ? new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies;
for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo))
{
// NOTE: In the case of PE symbols, it is possible to see an explicit implementation
// on a type that does not declare the corresponding interface (or one of its
// subinterfaces). In such cases, we want to return the explicit implementation,
// even if it doesn't participate in interface mapping according to the C# rules.
// pass 1: check for explicit impls (can't assume name matches)
MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember);
if (explicitImpl.Count == 1)
{
implementationInInterfacesMightChangeResult = false;
return explicitImpl.Single();
}
else if (explicitImpl.Count > 1)
{
if ((object)currType == implementingType || implementingTypeImplementsInterface)
{
diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember);
}
implementationInInterfacesMightChangeResult = false;
return null;
}
bool checkPendingExplicitImplementations = ((object)currType != implementingType || !currType.IsDefinition);
if (checkPendingExplicitImplementations && interfaceMember is MethodSymbol interfaceMethod &&
currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType))
{
// Check for implementations that are going to be explicit once types are emitted
MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod);
if (bodyOfSynthesizedMethodImpl is object)
{
implementationInInterfacesMightChangeResult = false;
return bodyOfSynthesizedMethodImpl;
}
}
if (IsExplicitlyImplementedViaAccessors(checkPendingExplicitImplementations, interfaceMember, currType, ref useSiteInfo, out Symbol currTypeExplicitImpl))
{
// We are looking for a property or event implementation and found an explicit implementation
// for its accessor(s) in this type. Stop the process and return event/property associated
// with the accessor(s), if any.
implementationInInterfacesMightChangeResult = false;
// NOTE: may be null.
return currTypeExplicitImpl;
}
if (!seenTypeDeclaringInterface ||
(!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null))
{
if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType))
{
if (!seenTypeDeclaringInterface)
{
implementingTypeIsFromSomeCompilation = currType.OriginalDefinition.ContainingModule is not PEModuleSymbol;
seenTypeDeclaringInterface = true;
}
if ((object)currType == implementingType)
{
implementingTypeImplementsInterface = true;
}
else if (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null)
{
implementingBaseOpt = currType;
}
}
}
// We want the implementation from the most derived type at or above the first one to
// include the interface (or a subinterface) in its interface list
if (seenTypeDeclaringInterface &&
(!interfaceMember.IsStatic || implementingTypeIsFromSomeCompilation))
{
//pass 2: check for implicit impls (name must match)
Symbol currTypeImplicitImpl;
Symbol currTypeCloseMismatch;
FindPotentialImplicitImplementationMemberDeclaredInType(
interfaceMember,
implementingTypeIsFromSomeCompilation,
currType,
out currTypeImplicitImpl,
out currTypeCloseMismatch);
if ((object)currTypeImplicitImpl != null)
{
implicitImpl = currTypeImplicitImpl;
break;
}
if ((object)closestMismatch == null)
{
closestMismatch = currTypeCloseMismatch;
}
}
}
Debug.Assert(!canBeImplementedImplicitlyInCSharp9 || (object)implementingBaseOpt == null);
bool tryDefaultInterfaceImplementation = !interfaceMember.IsStatic;
// Dev10 has some extra restrictions and extra wiggle room when finding implicit
// implementations for interface accessors. Perform some extra checks and possibly
// update the result (i.e. implicitImpl).
if (interfaceMember.IsAccessor())
{
Symbol originalImplicitImpl = implicitImpl;
CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl);
// If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate.
if (originalImplicitImpl is object && implicitImpl is null)
{
tryDefaultInterfaceImplementation = false;
}
}
Symbol defaultImpl = null;
if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation)
{
if (ignoreImplementationInInterfaces)
{
implementationInInterfacesMightChangeResult = true;
}
else
{
// Check for default interface implementations
defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics);
implementationInInterfacesMightChangeResult = false;
}
}
else
{
implementationInInterfacesMightChangeResult = false;
}
diagnostics.Add(
#if !DEBUG
// Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function.
useSiteInfo.Diagnostics is null || !implementingTypeImplementsInterface ? Location.None :
#endif
GetInterfaceLocation(interfaceMember, implementingType),
useSiteInfo);
if (defaultImpl is object)
{
if (implementingTypeImplementsInterface)
{
ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics);
}
return defaultImpl;
}
if (implementingTypeImplementsInterface)
{
if ((object)implicitImpl != null)
{
if (!canBeImplementedImplicitlyInCSharp9)
{
if (interfaceMember.Kind == SymbolKind.Method &&
(object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base.
{
LanguageVersion requiredVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion();
LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion;
if (requiredVersion > availableVersion)
{
diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType),
implementingType, interfaceMember, implicitImpl,
availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion));
}
}
}
ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics);
}
else if ((object)closestMismatch != null)
{
ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics);
}
}
return implicitImpl;
}
private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(!implementingType.IsInterfaceType());
Debug.Assert(!interfaceMember.IsStatic);
// If we are dealing with a property or event and an implementation of at least one accessor is not from an interface, it
// wouldn't be right to say that the event/property is implemented in an interface because its accessor isn't.
(MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember);
if (stopLookup(interfaceAccessor1, implementingType) || stopLookup(interfaceAccessor2, implementingType))
{
return null;
}
Symbol defaultImpl = FindMostSpecificImplementationInBases(interfaceMember,
implementingType,
ref useSiteInfo, out Symbol conflict1, out Symbol conflict2);
if ((object)conflict1 != null)
{
Debug.Assert((object)defaultImpl == null);
Debug.Assert((object)conflict2 != null);
diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType),
interfaceMember, conflict1, conflict2);
}
else
{
Debug.Assert(((object)conflict2 == null));
}
return defaultImpl;
static bool stopLookup(MethodSymbol interfaceAccessor, TypeSymbol implementingType)
{
if (interfaceAccessor is null)
{
return false;
}
SymbolAndDiagnostics symbolAndDiagnostics = implementingType.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceAccessor);
if (symbolAndDiagnostics.Symbol is object)
{
return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface;
}
// It is still possible that we actually looked for the accessor in interfaces, but failed due to an ambiguity.
// Let's try to look for a property to improve diagnostics in this scenario.
return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_MostSpecificImplementationIsNotFound);
}
}
private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface);
switch (implementingMember.Count)
{
case 0:
(MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember);
// If interface actually implements an event or property accessor, but doesn't implement the event/property,
// do not look for its implementation in bases.
if ((interfaceAccessor1 is object && FindImplementationInInterface(interfaceAccessor1, implementingInterface).Count != 0) ||
(interfaceAccessor2 is object && FindImplementationInInterface(interfaceAccessor2, implementingInterface).Count != 0))
{
return null;
}
return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface,
ref useSiteInfo,
out var _, out var _);
case 1:
{
Symbol result = implementingMember.Single();
if (result.IsAbstract)
{
return null;
}
return result;
}
default:
return null;
}
}
/// <summary>
/// One implementation M1 is considered more specific than another implementation M2
/// if M1 is declared on interface T1, M2 is declared on interface T2, and
/// T1 contains T2 among its direct or indirect interfaces.
/// </summary>
private static Symbol FindMostSpecificImplementationInBases(
Symbol interfaceMember,
TypeSymbol implementingType,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
out Symbol conflictingImplementation1,
out Symbol conflictingImplementation2)
{
ImmutableArray<NamedTypeSymbol> allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
if (allInterfaces.IsEmpty)
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
return null;
}
// Properties or events can be implemented in an unconventional manner, i.e. implementing accessors might not be tied to a property/event.
// If we simply look for a more specific implementing property/event, we might find one with not most specific implementing accessors.
// Returning a property/event like that would be incorrect because runtime will use most specific accessor, or it will fail because there will
// be an ambiguity for the accessor implementation.
// So, for events and properties we look for most specific implementation of corresponding accessors and then try to tie them back to
// an event/property, if any.
(MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember);
if (interfaceAccessor1 is null && interfaceAccessor2 is null)
{
return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2);
}
Symbol accessorImpl1 = findMostSpecificImplementationInBases(interfaceAccessor1 ?? interfaceAccessor2, allInterfaces, ref useSiteInfo,
out Symbol conflictingAccessorImplementation11, out Symbol conflictingAccessorImplementation12);
if (accessorImpl1 is null && conflictingAccessorImplementation11 is null) // implementation of accessor is not found
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
return null;
}
if (interfaceAccessor1 is null || interfaceAccessor2 is null)
{
if (accessorImpl1 is object)
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
return findImplementationInInterface(interfaceMember, accessorImpl1);
}
conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11);
conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12);
if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null))
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
}
return null;
}
Symbol accessorImpl2 = findMostSpecificImplementationInBases(interfaceAccessor2, allInterfaces, ref useSiteInfo,
out Symbol conflictingAccessorImplementation21, out Symbol conflictingAccessorImplementation22);
if ((accessorImpl2 is null && conflictingAccessorImplementation21 is null) || // implementation of accessor is not found
(accessorImpl1 is null) != (accessorImpl2 is null)) // there is most specific implementation for one accessor and an ambiguous implementation for the other accessor.
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
return null;
}
if (accessorImpl1 is object)
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
return findImplementationInInterface(interfaceMember, accessorImpl1, accessorImpl2);
}
conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11, conflictingAccessorImplementation21);
conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12, conflictingAccessorImplementation22);
if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null))
{
// One pair of conflicting accessors can be tied to an event/property, but the other cannot be tied to an event/property.
// Dropping conflict information since it only affects diagnostic.
conflictingImplementation1 = null;
conflictingImplementation2 = null;
}
return null;
static Symbol findImplementationInInterface(Symbol interfaceMember, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null)
{
NamedTypeSymbol implementingInterface = inplementingAccessor1.ContainingType;
if (implementingAccessor2 is object && !implementingInterface.Equals(implementingAccessor2.ContainingType, TypeCompareKind.ConsiderEverything))
{
// Implementing accessors are from different types, they cannot be tied to the same event/property.
return null;
}
MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface);
switch (implementingMember.Count)
{
case 1:
return implementingMember.Single();
default:
return null;
}
}
static Symbol findMostSpecificImplementationInBases(
Symbol interfaceMember,
ImmutableArray<NamedTypeSymbol> allInterfaces,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
out Symbol conflictingImplementation1,
out Symbol conflictingImplementation2)
{
var implementations = ArrayBuilder<(MultiDictionary<Symbol, Symbol>.ValueSet MethodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> Bases)>.GetInstance();
foreach (var interfaceType in allInterfaces)
{
if (!interfaceType.IsInterface)
{
// this code is reachable in error situations
continue;
}
MultiDictionary<Symbol, Symbol>.ValueSet candidate = FindImplementationInInterface(interfaceMember, interfaceType);
if (candidate.Count == 0)
{
continue;
}
for (int i = 0; i < implementations.Count; i++)
{
(MultiDictionary<Symbol, Symbol>.ValueSet methodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases) = implementations[i];
Symbol previous = methodSet.First();
NamedTypeSymbol previousContainingType = previous.ContainingType;
if (previousContainingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions))
{
// Last equivalent match wins
implementations[i] = (candidate, bases);
candidate = default;
break;
}
if (bases == null)
{
Debug.Assert(implementations.Count == 1);
bases = previousContainingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
implementations[i] = (methodSet, bases);
}
if (bases.ContainsKey(interfaceType))
{
// Previous candidate is more specific
candidate = default;
break;
}
}
if (candidate.Count == 0)
{
continue;
}
if (implementations.Count != 0)
{
MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases = interfaceType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
for (int i = implementations.Count - 1; i >= 0; i--)
{
if (bases.ContainsKey(implementations[i].MethodSet.First().ContainingType))
{
// new candidate is more specific
implementations.RemoveAt(i);
}
}
implementations.Add((candidate, bases));
}
else
{
implementations.Add((candidate, null));
}
}
Symbol result;
switch (implementations.Count)
{
case 0:
result = null;
conflictingImplementation1 = null;
conflictingImplementation2 = null;
break;
case 1:
MultiDictionary<Symbol, Symbol>.ValueSet methodSet = implementations[0].MethodSet;
switch (methodSet.Count)
{
case 1:
result = methodSet.Single();
if (result.IsAbstract)
{
result = null;
}
break;
default:
result = null;
break;
}
conflictingImplementation1 = null;
conflictingImplementation2 = null;
break;
default:
result = null;
conflictingImplementation1 = implementations[0].MethodSet.First();
conflictingImplementation2 = implementations[1].MethodSet.First();
break;
}
implementations.Free();
return result;
}
}
internal static MultiDictionary<Symbol, Symbol>.ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType)
{
Debug.Assert(interfaceType.IsInterface);
Debug.Assert(!interfaceMember.IsStatic);
NamedTypeSymbol containingType = interfaceMember.ContainingType;
if (containingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions))
{
if (!interfaceMember.IsAbstract)
{
if (!containingType.Equals(interfaceType, TypeCompareKind.ConsiderEverything))
{
interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType);
}
return new MultiDictionary<Symbol, Symbol>.ValueSet(interfaceMember);
}
return default;
}
return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember);
}
private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember)
{
MethodSymbol interfaceAccessor1;
MethodSymbol interfaceAccessor2;
switch (interfaceMember.Kind)
{
case SymbolKind.Property:
{
PropertySymbol interfaceProperty = (PropertySymbol)interfaceMember;
interfaceAccessor1 = interfaceProperty.GetMethod;
interfaceAccessor2 = interfaceProperty.SetMethod;
break;
}
case SymbolKind.Event:
{
EventSymbol interfaceEvent = (EventSymbol)interfaceMember;
interfaceAccessor1 = interfaceEvent.AddMethod;
interfaceAccessor2 = interfaceEvent.RemoveMethod;
break;
}
default:
{
interfaceAccessor1 = null;
interfaceAccessor2 = null;
break;
}
}
if (!interfaceAccessor1.IsImplementable())
{
interfaceAccessor1 = null;
}
if (!interfaceAccessor2.IsImplementable())
{
interfaceAccessor2 = null;
}
return (interfaceAccessor1, interfaceAccessor2);
}
/// <summary>
/// Since dev11 didn't expose a symbol API, it had the luxury of being able to accept a base class's claim that
/// it implements an interface. Roslyn, on the other hand, needs to be able to point to an implementing symbol
/// for each interface member.
///
/// DevDiv #718115 was triggered by some unusual metadata in a Microsoft reference assembly (Silverlight System.Windows.dll).
/// The issue was that a type explicitly implemented the accessors of an interface event, but did not tie them together with
/// an event declaration. To make matters worse, it declared its own protected event with the same name as the interface
/// event (presumably to back the explicit implementation). As a result, when Roslyn was asked to find the implementing member
/// for the interface event, it found the protected event and reported an appropriate diagnostic. What it should have done
/// (and does do now) is recognize that no event associated with the accessors explicitly implementing the interface accessors
/// and returned null.
///
/// We resolved this issue by introducing a new step into the interface mapping algorithm: after failing to find an explicit
/// implementation in a type, but before searching for an implicit implementation in that type, check for an explicit implementation
/// of an associated accessor. If there is such an implementation, then immediately return the associated property or event,
/// even if it is null. That is, never attempt to find an implicit implementation for an interface property or event with an
/// explicitly implemented accessor.
/// </summary>
private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol implementingMember)
{
(MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember);
Symbol associated1;
Symbol associated2;
if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor1, currType, ref useSiteInfo, out associated1) | // NB: not ||
TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out associated2))
{
// If there's more than one associated property/event, don't do anything special - just let the algorithm
// fail in the usual way.
if ((object)associated1 == null || (object)associated2 == null || associated1 == associated2)
{
implementingMember = associated1 ?? associated2;
// In source, we should already have seen an explicit implementation for the interface property/event.
// If we haven't then there is no implementation. We need this check to match dev11 in some edge cases
// (e.g. IndexerTests.AmbiguousExplicitIndexerImplementation). Such cases already fail
// to roundtrip correctly, so it's not important to check for a particular compilation.
if ((object)implementingMember != null && implementingMember.OriginalDefinition.ContainingModule is not PEModuleSymbol && implementingMember.IsExplicitInterfaceImplementation())
{
implementingMember = null;
}
}
else
{
implementingMember = null;
}
return true;
}
implementingMember = null;
return false;
}
private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol associated)
{
if ((object)interfaceAccessor != null)
{
// NB: uses a map that was built (and saved) when we checked for an explicit
// implementation of the interface member.
MultiDictionary<Symbol, Symbol>.ValueSet set = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor);
if (set.Count == 1)
{
Symbol implementation = set.Single();
associated = implementation.Kind == SymbolKind.Method
? ((MethodSymbol)implementation).AssociatedSymbol
: null;
return true;
}
if (checkPendingExplicitImplementations &&
currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType))
{
// Check for implementations that are going to be explicit once types are emitted
MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor);
if (bodyOfSynthesizedMethodImpl is object)
{
associated = bodyOfSynthesizedMethodImpl.AssociatedSymbol;
return true;
}
}
}
associated = null;
return false;
}
/// <summary>
/// If we were looking for an accessor, then look for an accessor on the implementation of the
/// corresponding interface property/event. If it is valid as an implementation (ignoring the name),
/// then prefer it to our current result if:
/// 1) our current result is null; or
/// 2) our current result is on the same type.
///
/// If there is no corresponding accessor on the implementation of the corresponding interface
/// property/event and we found an accessor, then the accessor we found is invalid, so clear it.
/// </summary>
private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation,
ref Symbol implicitImpl)
{
Debug.Assert(!implementingType.IsInterfaceType());
Debug.Assert(interfaceMethod.IsAccessor());
Symbol associatedInterfacePropertyOrEvent = interfaceMethod.AssociatedSymbol;
// Do not make any adjustments based on presence of default interface implementation for the property or event.
// We don't want an addition of default interface implementation to change an error situation to success for
// scenarios where the default interface implementation wouldn't actually be used at runtime.
// When we find an implicit implementation candidate, we don't want to not discard it if we would discard it when
// default interface implementation was missing. Why would presence of default interface implementation suddenly
// make the candidate suiatable to implement the interface? Also, if we discard the candidate, we don't want default interface
// implementation to take over later, since runtime might still use the discarded candidate.
// When we don't find any implicit implementation candidate, returning accessor of default interface implementation
// doesn't actually help much because we would find it anyway (it is implemented explicitly).
Symbol implementingPropertyOrEvent = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedInterfacePropertyOrEvent,
ignoreImplementationInInterfacesIfResultIsNotReady: true); // NB: uses cache
MethodSymbol correspondingImplementingAccessor = null;
if ((object)implementingPropertyOrEvent != null && !implementingPropertyOrEvent.ContainingType.IsInterface)
{
switch (interfaceMethod.MethodKind)
{
case MethodKind.PropertyGet:
correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedGetMethod();
break;
case MethodKind.PropertySet:
correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedSetMethod();
break;
case MethodKind.EventAdd:
correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedAddMethod();
break;
case MethodKind.EventRemove:
correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedRemoveMethod();
break;
default:
throw ExceptionUtilities.UnexpectedValue(interfaceMethod.MethodKind);
}
}
if (correspondingImplementingAccessor == implicitImpl)
{
return;
}
else if ((object)correspondingImplementingAccessor == null && (object)implicitImpl != null && implicitImpl.IsAccessor())
{
// If we found an accessor, but it's not (directly or indirectly) on the property implementation,
// then it's not a valid match.
implicitImpl = null;
}
else if ((object)correspondingImplementingAccessor != null && ((object)implicitImpl == null || TypeSymbol.Equals(correspondingImplementingAccessor.ContainingType, implicitImpl.ContainingType, TypeCompareKind.ConsiderEverything2)))
{
// Suppose the interface accessor and the implementing accessor have different names.
// In Dev10, as long as the corresponding properties have an implementation relationship,
// then the accessor can be considered an implementation, even though the name is different.
// Later on, when we check that implementation signatures match exactly
// (in SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation),
// they won't (because of the names) and an explicit implementation method will be synthesized.
MethodSymbol interfaceAccessorWithImplementationName = new SignatureOnlyMethodSymbol(
correspondingImplementingAccessor.Name,
interfaceMethod.ContainingType,
interfaceMethod.MethodKind,
interfaceMethod.CallingConvention,
interfaceMethod.TypeParameters,
interfaceMethod.Parameters,
interfaceMethod.RefKind,
interfaceMethod.IsInitOnly,
interfaceMethod.IsStatic,
interfaceMethod.ReturnTypeWithAnnotations,
interfaceMethod.RefCustomModifiers,
interfaceMethod.ExplicitInterfaceImplementations);
// Make sure that the corresponding accessor is a real implementation.
if (IsInterfaceMemberImplementation(correspondingImplementingAccessor, interfaceAccessorWithImplementationName, implementingTypeIsFromSomeCompilation))
{
implicitImpl = correspondingImplementingAccessor;
}
}
}
private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics)
{
if (interfaceMember.Kind == SymbolKind.Method && implementingType.ContainingModule != implicitImpl.ContainingModule)
{
// The default implementation is coming from a different module, which means that we probably didn't check
// for the required runtime capability or language version
LanguageVersion requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion();
LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion;
if (requiredVersion > availableVersion)
{
diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember,
GetInterfaceLocation(interfaceMember, implementingType),
implicitImpl, interfaceMember, implementingType,
MessageID.IDS_DefaultInterfaceImplementation.Localize(),
availableVersion.GetValueOrDefault().ToDisplayString(),
new CSharpRequiredLanguageVersion(requiredVersion));
}
if (!implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation)
{
diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember,
GetInterfaceLocation(interfaceMember, implementingType),
implicitImpl, interfaceMember, implementingType);
}
}
}
/// <summary>
/// These diagnostics are for members that do implicitly implement an interface member, but do so
/// in an undesirable way.
/// </summary>
private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics)
{
bool reportedAnError = false;
if (interfaceMember.Kind == SymbolKind.Method)
{
var interfaceMethod = (MethodSymbol)interfaceMember;
bool implicitImplIsAccessor = implicitImpl.IsAccessor();
bool interfaceMethodIsAccessor = interfaceMethod.IsAccessor();
if (interfaceMethodIsAccessor && !implicitImplIsAccessor && !interfaceMethod.IsIndexedPropertyAccessor())
{
diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType);
}
else if (!interfaceMethodIsAccessor && implicitImplIsAccessor)
{
diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType);
}
else
{
var implicitImplMethod = (MethodSymbol)implicitImpl;
if (implicitImplMethod.IsConditional)
{
// CS0629: Conditional member '{0}' cannot implement interface member '{1}' in type '{2}'
diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType);
}
else if (implicitImplMethod.IsStatic && implicitImplMethod.MethodKind == MethodKind.Ordinary && implicitImplMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is not null)
{
diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType);
}
else if (ReportAnyMismatchedConstraints(interfaceMethod, implementingType, implicitImplMethod, diagnostics))
{
reportedAnError = true;
}
}
}
if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember))
{
// it is ok to implement implicitly with no tuple names, for compatibility with C# 6, but otherwise names should match
diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember);
reportedAnError = true;
}
if (!reportedAnError && implementingType.DeclaringCompilation != null)
{
CheckNullableReferenceTypeMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics);
}
// In constructed types, it is possible to see multiple members with the same (runtime) signature.
// Now that we know which member will implement the interface member, confirm that it is the only
// such member.
if (!implicitImpl.ContainingType.IsDefinition)
{
foreach (Symbol member in implicitImpl.ContainingType.GetMembers(implicitImpl.Name))
{
if (member.DeclaredAccessibility != Accessibility.Public || member.IsStatic || member == implicitImpl)
{
//do nothing - not an ambiguous implementation
}
else if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, member) && !member.IsAccessor())
{
// CONSIDER: Dev10 does not seem to report this for indexers or their accessors.
diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, member), member, interfaceMember, implementingType);
}
}
}
if (implicitImpl.IsStatic && !implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces)
{
diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember,
GetInterfaceLocation(interfaceMember, implementingType),
implicitImpl, interfaceMember, implementingType);
}
}
internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics)
{
if (!implementingMember.IsImplicitlyDeclared && !implementingMember.IsAccessor())
{
CSharpCompilation compilation = implementingType.DeclaringCompilation;
if (interfaceMember.Kind == SymbolKind.Event)
{
var implementingEvent = (EventSymbol)implementingMember;
var implementedEvent = (EventSymbol)interfaceMember;
SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(compilation, implementedEvent, implementingEvent,
diagnostics,
(diagnostics, implementedEvent, implementingEvent, arg) =>
{
if (arg.isExplicit)
{
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation,
implementingEvent.Locations[0], new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
else
{
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation,
GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent),
new FormattedSymbol(implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat),
new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
},
(implementingType, isExplicit));
}
else
{
ReportMismatchInReturnType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInReturnType =
(diagnostics, implementedMethod, implementingMethod, topLevel, arg) =>
{
if (arg.isExplicit)
{
// We use ConstructedFrom symbols here and below to not leak methods with Ignored annotations in type arguments
// into diagnostics
diagnostics.Add(topLevel ?
ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation :
ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation,
implementingMethod.Locations[0], new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
else
{
diagnostics.Add(topLevel ?
ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation :
ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation,
GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod),
new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat),
new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
};
ReportMismatchInParameterType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInParameterType =
(diagnostics, implementedMethod, implementingMethod, implementingParameter, topLevel, arg) =>
{
if (arg.isExplicit)
{
diagnostics.Add(topLevel ?
ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation :
ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation,
implementingMethod.Locations[0],
new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat),
new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
else
{
diagnostics.Add(topLevel ?
ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation :
ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation,
GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod),
new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat),
new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat),
new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
};
switch (interfaceMember.Kind)
{
case SymbolKind.Property:
var implementingProperty = (PropertySymbol)implementingMember;
var implementedProperty = (PropertySymbol)interfaceMember;
if (implementedProperty.GetMethod.IsImplementable())
{
MethodSymbol implementingGetMethod = implementingProperty.GetOwnOrInheritedGetMethod();
SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(
compilation,
implementedProperty.GetMethod,
implementingGetMethod,
diagnostics,
reportMismatchInReturnType,
// Don't check parameters on the getter if there is a setter
// because they will be a subset of the setter
(!implementedProperty.SetMethod.IsImplementable() ||
implementingGetMethod?.AssociatedSymbol != implementingProperty ||
implementingProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != implementingProperty) ? reportMismatchInParameterType : null,
(implementingType, isExplicit));
}
if (implementedProperty.SetMethod.IsImplementable())
{
SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(
compilation,
implementedProperty.SetMethod,
implementingProperty.GetOwnOrInheritedSetMethod(),
diagnostics,
null,
reportMismatchInParameterType,
(implementingType, isExplicit));
}
break;
case SymbolKind.Method:
var implementingMethod = (MethodSymbol)implementingMember;
var implementedMethod = (MethodSymbol)interfaceMember;
if (implementedMethod.IsGenericMethod)
{
implementedMethod = implementedMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementingMethod.TypeParameters));
}
SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(
compilation,
implementedMethod,
implementingMethod,
diagnostics,
reportMismatchInReturnType,
reportMismatchInParameterType,
(implementingType, isExplicit));
break;
default:
throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind);
}
}
}
}
/// <summary>
/// These diagnostics are for members that almost, but not actually, implicitly implement an interface member.
/// </summary>
private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics)
{
// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class.
Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType);
if (closestMismatch.IsStatic != interfaceMember.IsStatic)
{
diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic,
interfaceLocation, implementingType, interfaceMember, closestMismatch);
}
else if (closestMismatch.DeclaredAccessibility != Accessibility.Public)
{
ErrorCode errorCode = interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic;
diagnostics.Add(errorCode, interfaceLocation, implementingType, interfaceMember, closestMismatch);
}
else if (HaveInitOnlyMismatch(interfaceMember, closestMismatch))
{
diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch);
}
else //return ref kind or type doesn't match
{
RefKind interfaceMemberRefKind = RefKind.None;
TypeSymbol interfaceMemberReturnType;
switch (interfaceMember.Kind)
{
case SymbolKind.Method:
var method = (MethodSymbol)interfaceMember;
interfaceMemberRefKind = method.RefKind;
interfaceMemberReturnType = method.ReturnType;
break;
case SymbolKind.Property:
var property = (PropertySymbol)interfaceMember;
interfaceMemberRefKind = property.RefKind;
interfaceMemberReturnType = property.Type;
break;
case SymbolKind.Event:
interfaceMemberReturnType = ((EventSymbol)interfaceMember).Type;
break;
default:
throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind);
}
bool hasRefReturnMismatch = false;
switch (closestMismatch.Kind)
{
case SymbolKind.Method:
hasRefReturnMismatch = ((MethodSymbol)closestMismatch).RefKind != interfaceMemberRefKind;
break;
case SymbolKind.Property:
hasRefReturnMismatch = ((PropertySymbol)closestMismatch).RefKind != interfaceMemberRefKind;
break;
}
DiagnosticInfo useSiteDiagnostic;
if ((object)interfaceMemberReturnType != null &&
(useSiteDiagnostic = interfaceMemberReturnType.GetUseSiteInfo().DiagnosticInfo) != null &&
useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error)
{
diagnostics.Add(useSiteDiagnostic, interfaceLocation);
}
else if (hasRefReturnMismatch)
{
diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch);
}
else
{
diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, interfaceMemberReturnType);
}
}
}
internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other)
{
if (!(one is MethodSymbol oneMethod))
{
return false;
}
if (!(other is MethodSymbol otherMethod))
{
return false;
}
return oneMethod.IsInitOnly != otherMethod.IsInitOnly;
}
/// <summary>
/// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class.
/// </summary>
private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType)
{
Debug.Assert((object)implementingType != null);
var @interface = interfaceMember.ContainingType;
SourceMemberContainerTypeSymbol snt = null;
if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface].Contains(@interface))
{
snt = implementingType as SourceMemberContainerTypeSymbol;
}
return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations.FirstOrNone();
}
private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics)
{
Debug.Assert(interfaceMethod.Arity == implicitImpl.Arity);
bool result = false;
var arity = interfaceMethod.Arity;
if (arity > 0)
{
var typeParameters1 = interfaceMethod.TypeParameters;
var typeParameters2 = implicitImpl.TypeParameters;
var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity);
var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true);
var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true);
// Report any mismatched method constraints.
for (int i = 0; i < arity; i++)
{
var typeParameter1 = typeParameters1[i];
var typeParameter2 = typeParameters2[i];
if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2))
{
// If the matching method for the interface member is defined on the implementing type,
// the matching method location is used for the error. Otherwise, the location of the
// implementing type is used. (This differs from Dev10 which associates the error with
// the closest method always. That behavior can be confusing though, since in the case
// of "interface I { M; } class A { M; } class B : A, I { }", this means reporting an error on
// A.M that it does not satisfy I.M even though A does not implement I. Furthermore if
// A is defined in metadata, there is no location for A.M. Instead, we simply report the
// error on B if the match to I.M is in a base class.)
diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod);
}
else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2))
{
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl),
typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod);
}
}
}
return result;
}
internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member)
{
if (TypeSymbol.Equals(member.ContainingType, implementingType, TypeCompareKind.ConsiderEverything2))
{
return member.Locations[0];
}
else
{
var @interface = interfaceMember.ContainingType;
SourceMemberContainerTypeSymbol snt = implementingType as SourceMemberContainerTypeSymbol;
return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations[0];
}
}
/// <summary>
/// Search the declared members of a type for one that could be an implementation
/// of a given interface member (depending on interface declarations).
/// </summary>
/// <param name="interfaceMember">The interface member being implemented.</param>
/// <param name="implementingTypeIsFromSomeCompilation">True if the implementing type is from some compilation (i.e. not from metadata).</param>
/// <param name="currType">The type on which we are looking for a declared implementation of the interface member.</param>
/// <param name="implicitImpl">A member on currType that could implement the interface, or null.</param>
/// <param name="closeMismatch">A member on currType that could have been an attempt to implement the interface, or null.</param>
/// <remarks>
/// There is some similarity between this member and OverriddenOrHiddenMembersHelpers.FindOverriddenOrHiddenMembersInType.
/// When making changes to this member, think about whether or not they should also be applied in MemberSymbol.
/// One key difference is that custom modifiers are considered when looking up overridden members, but
/// not when looking up implicit implementations. We're preserving this behavior from Dev10.
/// </remarks>
private static void FindPotentialImplicitImplementationMemberDeclaredInType(
Symbol interfaceMember,
bool implementingTypeIsFromSomeCompilation,
TypeSymbol currType,
out Symbol implicitImpl,
out Symbol closeMismatch)
{
implicitImpl = null;
closeMismatch = null;
bool? isOperator = null;
if (interfaceMember is MethodSymbol interfaceMethod)
{
isOperator = interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion;
}
foreach (Symbol member in currType.GetMembers(interfaceMember.Name))
{
if (member.Kind == interfaceMember.Kind)
{
if (isOperator.HasValue &&
(((MethodSymbol)member).MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator.GetValueOrDefault())
{
continue;
}
if (IsInterfaceMemberImplementation(member, interfaceMember, implementingTypeIsFromSomeCompilation))
{
implicitImpl = member;
return;
}
// If we haven't found a match, do a weaker comparison that ignores static-ness, accessibility, and return type.
else if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation)
{
// We can ignore custom modifiers here, because our goal is to improve the helpfulness
// of an error we're already giving, rather than to generate a new error.
if (MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, member))
{
closeMismatch = member;
}
}
}
}
}
/// <summary>
/// To implement an interface member, a candidate member must be public, non-static, and have
/// the same signature. "Have the same signature" has a looser definition if the type implementing
/// the interface is from source.
/// </summary>
/// <remarks>
/// PROPERTIES:
/// NOTE: we're not checking whether this property has at least the accessors
/// declared in the interface. Dev10 considers it a match either way and,
/// reports failure to implement accessors separately.
///
/// If the implementing type (i.e. the type with the interface in its interface
/// list) is in source, then we can ignore custom modifiers in/on the property
/// type because they will be copied into the bridge property that explicitly
/// implements the interface property (or they would be, if we created such
/// a bridge property). Bridge *methods* (not properties) are inserted in
/// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation.
///
/// CONSIDER: The spec for interface mapping (13.4.4) could be interpreted to mean that this
/// property is not an implementation unless it has an accessor for each accessor of the
/// interface property. For now, we prefer to represent that case as having an implemented
/// property and an unimplemented accessor because it makes finding accessor implementations
/// much easier. If we decide that we want the API to report the property as unimplemented,
/// then it might be appropriate to keep current result internally and just check the accessors
/// before returning the value from the public API (similar to the way MethodSymbol.OverriddenMethod
/// filters MethodSymbol.OverriddenOrHiddenMembers.
/// </remarks>
private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation)
{
if (candidateMember.DeclaredAccessibility != Accessibility.Public || candidateMember.IsStatic != interfaceMember.IsStatic)
{
return false;
}
else if (HaveInitOnlyMismatch(candidateMember, interfaceMember))
{
return false;
}
else if (implementingTypeIsFromSomeCompilation)
{
// We're specifically ignoring custom modifiers for source types because that's what Dev10 does.
// Inexact matches are acceptable because we'll just generate bridge members - explicit implementations
// with exact signatures that delegate to the inexact match. This happens automatically in
// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation.
return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember);
}
else
{
// NOTE: Dev10 seems to use the C# rules in this case as well, but it doesn't give diagnostics about
// the failure of a metadata type to implement an interface so there's no problem with reporting the
// CLI interpretation instead. For example, using this comparer might allow a member with a ref
// parameter to implement a member with an out parameter - which Dev10 would not allow - but that's
// okay because Dev10's behavior is not observable.
return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember);
}
}
protected MultiDictionary<Symbol, Symbol>.ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember)
{
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
return default;
}
if (info.explicitInterfaceImplementationMap == null)
{
Interlocked.CompareExchange(ref info.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null);
}
return info.explicitInterfaceImplementationMap[interfaceMember];
}
private MultiDictionary<Symbol, Symbol> MakeExplicitInterfaceImplementationMap()
{
var map = new MultiDictionary<Symbol, Symbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance);
foreach (var member in this.GetMembersUnordered())
{
foreach (var interfaceMember in member.GetExplicitInterfaceImplementations())
{
Debug.Assert(interfaceMember.Kind != SymbolKind.Method || (object)interfaceMember == ((MethodSymbol)interfaceMember).ConstructedFrom);
map.Add(interfaceMember, member);
}
}
return map;
}
#nullable enable
/// <summary>
/// If implementation of an interface method <paramref name="interfaceMethod"/> will be accompanied with
/// a MethodImpl entry in metadata, information about which isn't already exposed through
/// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API, this method returns the "Body" part
/// of the MethodImpl entry, i.e. the method that implements the <paramref name="interfaceMethod"/>.
/// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases,
/// the result is the method that the language considers to implement the <paramref name="interfaceMethod"/>,
/// rather than the forwarding method. In other words, it is the method that the forwarding method forwards to.
/// </summary>
/// <param name="interfaceMethod">The interface method that is going to be implemented by using synthesized MethodImpl entry.</param>
/// <returns></returns>
protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod)
{
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
return null;
}
if (info.synthesizedMethodImplMap == null)
{
Interlocked.CompareExchange(ref info.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null);
}
if (info.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol? result))
{
return result;
}
return null;
ImmutableDictionary<MethodSymbol, MethodSymbol> makeSynthesizedMethodImplMap()
{
var map = ImmutableDictionary.CreateBuilder<MethodSymbol, MethodSymbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance);
foreach ((MethodSymbol body, MethodSymbol implemented) in this.SynthesizedInterfaceMethodImpls())
{
map.Add(implemented, body);
}
return map.ToImmutable();
}
}
/// <summary>
/// Returns information about interface method implementations that will be accompanied with
/// MethodImpl entries in metadata, information about which isn't already exposed through
/// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API. The "Body" is the method that
/// implements the interface method "Implemented".
/// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases,
/// the "Body" is the method that the language considers to implement the interface method,
/// the "Implemented", rather than the forwarding method. In other words, it is the method that
/// the forwarding method forwards to.
/// </summary>
internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls();
#nullable disable
protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer<Symbol>
{
public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer();
private ExplicitInterfaceImplementationTargetMemberEqualityComparer() { }
public bool Equals(Symbol x, Symbol y)
{
return x.OriginalDefinition == y.OriginalDefinition &&
x.ContainingType.Equals(y.ContainingType, TypeCompareKind.CLRSignatureCompareOptions);
}
public int GetHashCode(Symbol obj)
{
return obj.OriginalDefinition.GetHashCode();
}
}
#endregion Interface member checks
#region Abstract base type checks
/// <summary>
/// The set of abstract members in declared in this type or declared in a base type and not overridden.
/// </summary>
internal ImmutableHashSet<Symbol> AbstractMembers
{
get
{
if (_lazyAbstractMembers == null)
{
Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null);
}
return _lazyAbstractMembers;
}
}
private ImmutableHashSet<Symbol> ComputeAbstractMembers()
{
var abstractMembers = ImmutableHashSet.Create<Symbol>();
var overriddenMembers = ImmutableHashSet.Create<Symbol>();
foreach (var member in this.GetMembersUnordered())
{
if (this.IsAbstract && member.IsAbstract && member.Kind != SymbolKind.NamedType)
{
abstractMembers = abstractMembers.Add(member);
}
Symbol overriddenMember = null;
switch (member.Kind)
{
case SymbolKind.Method:
{
overriddenMember = ((MethodSymbol)member).OverriddenMethod;
break;
}
case SymbolKind.Property:
{
overriddenMember = ((PropertySymbol)member).OverriddenProperty;
break;
}
case SymbolKind.Event:
{
overriddenMember = ((EventSymbol)member).OverriddenEvent;
break;
}
}
if ((object)overriddenMember != null)
{
overriddenMembers = overriddenMembers.Add(overriddenMember);
}
}
if ((object)this.BaseTypeNoUseSiteDiagnostics != null && this.BaseTypeNoUseSiteDiagnostics.IsAbstract)
{
foreach (var baseAbstractMember in this.BaseTypeNoUseSiteDiagnostics.AbstractMembers)
{
if (!overriddenMembers.Contains(baseAbstractMember))
{
abstractMembers = abstractMembers.Add(baseAbstractMember);
}
}
}
return abstractMembers;
}
#endregion Abstract base type checks
[Obsolete("Use TypeWithAnnotations.Is method.", true)]
internal bool Equals(TypeWithAnnotations other)
{
throw ExceptionUtilities.Unreachable;
}
public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison)
{
if (left is null)
{
return right is null;
}
return left.Equals(right, comparison);
}
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator ==(TypeSymbol left, TypeSymbol right)
=> throw ExceptionUtilities.Unreachable;
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator !=(TypeSymbol left, TypeSymbol right)
=> throw ExceptionUtilities.Unreachable;
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator ==(Symbol left, TypeSymbol right)
=> throw ExceptionUtilities.Unreachable;
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator !=(Symbol left, TypeSymbol right)
=> throw ExceptionUtilities.Unreachable;
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator ==(TypeSymbol left, Symbol right)
=> throw ExceptionUtilities.Unreachable;
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator !=(TypeSymbol left, Symbol right)
=> throw ExceptionUtilities.Unreachable;
internal ITypeSymbol GetITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
if (nullableAnnotation == DefaultNullableAnnotation)
{
return (ITypeSymbol)this.ISymbol;
}
return CreateITypeSymbol(nullableAnnotation);
}
internal CodeAnalysis.NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious);
protected abstract ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation);
TypeKind ITypeSymbolInternal.TypeKind => this.TypeKind;
SpecialType ITypeSymbolInternal.SpecialType => this.SpecialType;
bool ITypeSymbolInternal.IsReferenceType => this.IsReferenceType;
bool ITypeSymbolInternal.IsValueType => this.IsValueType;
ITypeSymbol ITypeSymbolInternal.GetITypeSymbol()
{
return GetITypeSymbol(DefaultNullableAnnotation);
}
internal abstract bool IsRecord { get; }
internal abstract bool IsRecordStruct { 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.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
#pragma warning disable CS0660
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A TypeSymbol is a base class for all the symbols that represent a type
/// in C#.
/// </summary>
internal abstract partial class TypeSymbol : NamespaceOrTypeSymbol, ITypeSymbolInternal
{
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// 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.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// TODO (tomat): Consider changing this to an empty name. This name shouldn't ever leak to the user in error messages.
internal const string ImplicitTypeName = "<invalid-global-code>";
// InterfaceInfo for a common case of a type not implementing anything directly or indirectly.
private static readonly InterfaceInfo s_noInterfaces = new InterfaceInfo();
private ImmutableHashSet<Symbol> _lazyAbstractMembers;
private InterfaceInfo _lazyInterfaceInfo;
private class InterfaceInfo
{
// all directly implemented interfaces, their bases and all interfaces to the bases of the type recursively
internal ImmutableArray<NamedTypeSymbol> allInterfaces;
/// <summary>
/// <see cref="TypeSymbol.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics"/>
/// </summary>
internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBaseInterfaces;
internal static readonly MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> EmptyInterfacesAndTheirBaseInterfaces =
new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(0, SymbolEqualityComparer.CLRSignature);
// Key is implemented member (method, property, or event), value is implementing member (from the
// perspective of this type). Don't allocate until someone needs it.
private ConcurrentDictionary<Symbol, SymbolAndDiagnostics> _implementationForInterfaceMemberMap;
public ConcurrentDictionary<Symbol, SymbolAndDiagnostics> ImplementationForInterfaceMemberMap
{
get
{
var map = _implementationForInterfaceMemberMap;
if (map != null)
{
return map;
}
// PERF: Avoid over-allocation. In many cases, there's only 1 entry and we don't expect concurrent updates.
map = new ConcurrentDictionary<Symbol, SymbolAndDiagnostics>(concurrencyLevel: 1, capacity: 1, comparer: SymbolEqualityComparer.ConsiderEverything);
return Interlocked.CompareExchange(ref _implementationForInterfaceMemberMap, map, null) ?? map;
}
}
/// <summary>
/// key = interface method/property/event compared using <see cref="ExplicitInterfaceImplementationTargetMemberEqualityComparer"/>,
/// value = explicitly implementing methods/properties/events declared on this type (normally a single value, multiple in case of
/// an error).
/// </summary>
internal MultiDictionary<Symbol, Symbol> explicitInterfaceImplementationMap;
#nullable enable
internal ImmutableDictionary<MethodSymbol, MethodSymbol>? synthesizedMethodImplMap;
#nullable disable
internal bool IsDefaultValue()
{
return allInterfaces.IsDefault &&
interfacesAndTheirBaseInterfaces == null &&
_implementationForInterfaceMemberMap == null &&
explicitInterfaceImplementationMap == null &&
synthesizedMethodImplMap == null;
}
}
private InterfaceInfo GetInterfaceInfo()
{
var info = _lazyInterfaceInfo;
if (info != null)
{
Debug.Assert(info != s_noInterfaces || info.IsDefaultValue(), "default value was modified");
return info;
}
for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics)
{
var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics();
if (!interfaces.IsEmpty)
{
// it looks like we or one of our bases implements something.
info = new InterfaceInfo();
// NOTE: we are assigning lazyInterfaceInfo via interlocked not for correctness,
// we just do not want to override an existing info that could be partially filled.
return Interlocked.CompareExchange(ref _lazyInterfaceInfo, info, null) ?? info;
}
}
// if we have got here it means neither we nor our bases implement anything
_lazyInterfaceInfo = info = s_noInterfaces;
return info;
}
/// <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 TypeSymbol OriginalDefinition
{
get
{
return OriginalTypeSymbolDefinition;
}
}
protected virtual TypeSymbol OriginalTypeSymbolDefinition
{
get
{
return this;
}
}
protected sealed override Symbol OriginalSymbolDefinition
{
get
{
return this.OriginalTypeSymbolDefinition;
}
}
/// <summary>
/// Gets the BaseType of this type. If the base type could not be determined, then
/// an instance of ErrorType is returned. If this kind of type does not have a base type
/// (for example, interfaces), null is returned. Also the special class System.Object
/// always has a BaseType of null.
/// </summary>
internal abstract NamedTypeSymbol BaseTypeNoUseSiteDiagnostics { get; }
internal NamedTypeSymbol BaseTypeWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var result = BaseTypeNoUseSiteDiagnostics;
if ((object)result != null)
{
result.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo);
}
return result;
}
internal NamedTypeSymbol BaseTypeOriginalDefinition(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var result = BaseTypeNoUseSiteDiagnostics;
if ((object)result != null)
{
result = result.OriginalDefinition;
result.AddUseSiteInfo(ref useSiteInfo);
}
return result;
}
/// <summary>
/// Gets the set of interfaces that this type directly implements. This set does not include
/// interfaces that are base interfaces of directly implemented interfaces.
/// </summary>
internal abstract ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved = null);
/// <summary>
/// The list of all interfaces of which this type is a declared subtype, excluding this type
/// itself. This includes all declared base interfaces, all declared base interfaces of base
/// types, and all declared base interfaces of those results (recursively). Each result
/// appears exactly once in the list. This list is topologically sorted by the inheritance
/// relationship: if interface type A extends interface type B, then A precedes B in the
/// list. This is not quite the same as "all interfaces of which this type is a proper
/// subtype" because it does not take into account variance: AllInterfaces for
/// IEnumerable<string> will not include IEnumerable<object>
/// </summary>
internal ImmutableArray<NamedTypeSymbol> AllInterfacesNoUseSiteDiagnostics
{
get
{
return GetAllInterfaces();
}
}
internal ImmutableArray<NamedTypeSymbol> AllInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var result = AllInterfacesNoUseSiteDiagnostics;
// Since bases affect content of AllInterfaces set, we need to make sure they all are good.
var current = this;
do
{
current = current.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
}
while ((object)current != null);
foreach (var iface in result)
{
iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo);
}
return result;
}
/// <summary>
/// If this is a type parameter returns its effective base class, otherwise returns this type.
/// </summary>
internal TypeSymbol EffectiveTypeNoUseSiteDiagnostics
{
get
{
return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClassNoUseSiteDiagnostics : this;
}
}
internal TypeSymbol EffectiveType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
return this.IsTypeParameter() ? ((TypeParameterSymbol)this).EffectiveBaseClass(ref useSiteInfo) : this;
}
/// <summary>
/// Returns true if this type derives from a given type.
/// </summary>
internal bool IsDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert((object)type != null);
Debug.Assert(!type.IsTypeParameter());
if ((object)this == (object)type)
{
return false;
}
var t = this.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
while ((object)t != null)
{
if (type.Equals(t, comparison))
{
return true;
}
t = t.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
}
return false;
}
/// <summary>
/// Returns true if this type is equal or derives from a given type.
/// </summary>
internal bool IsEqualToOrDerivedFrom(TypeSymbol type, TypeCompareKind comparison, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
return this.Equals(type, comparison) || this.IsDerivedFrom(type, comparison, ref useSiteInfo);
}
/// <summary>
/// Determines if this type symbol represent the same type as another, according to the language
/// semantics.
/// </summary>
/// <param name="t2">The other type.</param>
/// <param name="compareKind">
/// What kind of comparison to use?
/// You can ignore custom modifiers, ignore the distinction between object and dynamic, or ignore tuple element names differences.
/// </param>
/// <returns>True if the types are equivalent.</returns>
internal virtual bool Equals(TypeSymbol t2, TypeCompareKind compareKind)
{
return ReferenceEquals(this, t2);
}
public sealed override bool Equals(Symbol other, TypeCompareKind compareKind)
{
var t2 = other as TypeSymbol;
if (t2 is null)
{
return false;
}
return this.Equals(t2, compareKind);
}
/// <summary>
/// We ignore custom modifiers, and the distinction between dynamic and object, when computing a type's hash code.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
protected virtual ImmutableArray<NamedTypeSymbol> GetAllInterfaces()
{
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
if (info.allInterfaces.IsDefault)
{
ImmutableInterlocked.InterlockedInitialize(ref info.allInterfaces, MakeAllInterfaces());
}
return info.allInterfaces;
}
/// Produce all implemented interfaces in topologically sorted order. We use
/// TypeSymbol.Interfaces as the source of edge data, which has had cycles and infinitely
/// long dependency cycles removed. Consequently, it is possible (and we do) use the
/// simplest version of Tarjan's topological sorting algorithm.
protected virtual ImmutableArray<NamedTypeSymbol> MakeAllInterfaces()
{
var result = ArrayBuilder<NamedTypeSymbol>.GetInstance();
var visited = new HashSet<NamedTypeSymbol>(SymbolEqualityComparer.ConsiderEverything);
for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics)
{
var interfaces = (baseType.TypeKind == TypeKind.TypeParameter) ? ((TypeParameterSymbol)baseType).EffectiveInterfacesNoUseSiteDiagnostics : baseType.InterfacesNoUseSiteDiagnostics();
for (int i = interfaces.Length - 1; i >= 0; i--)
{
addAllInterfaces(interfaces[i], visited, result);
}
}
result.ReverseContents();
return result.ToImmutableAndFree();
static void addAllInterfaces(NamedTypeSymbol @interface, HashSet<NamedTypeSymbol> visited, ArrayBuilder<NamedTypeSymbol> result)
{
if (visited.Add(@interface))
{
ImmutableArray<NamedTypeSymbol> baseInterfaces = @interface.InterfacesNoUseSiteDiagnostics();
for (int i = baseInterfaces.Length - 1; i >= 0; i--)
{
var baseInterface = baseInterfaces[i];
addAllInterfaces(baseInterface, visited, result);
}
result.Add(@interface);
}
}
}
/// <summary>
/// Gets the set of interfaces that this type directly implements, plus the base interfaces
/// of all such types. Keys are compared using <see cref="SymbolEqualityComparer.CLRSignature"/>,
/// values are distinct interfaces corresponding to the key, according to <see cref="TypeCompareKind.ConsiderEverything"/> rules.
/// </summary>
/// <remarks>
/// CONSIDER: it probably isn't truly necessary to cache this. If space gets tight, consider
/// alternative approaches (recompute every time, cache on the side, only store on some types,
/// etc).
/// </remarks>
internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics
{
get
{
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
Debug.Assert(InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces.IsEmpty);
return InterfaceInfo.EmptyInterfacesAndTheirBaseInterfaces;
}
if (info.interfacesAndTheirBaseInterfaces == null)
{
Interlocked.CompareExchange(ref info.interfacesAndTheirBaseInterfaces, MakeInterfacesAndTheirBaseInterfaces(this.InterfacesNoUseSiteDiagnostics()), null);
}
return info.interfacesAndTheirBaseInterfaces;
}
}
internal MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
var result = InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics;
foreach (var iface in result.Keys)
{
iface.OriginalDefinition.AddUseSiteInfo(ref useSiteInfo);
}
return result;
}
// Note: Unlike MakeAllInterfaces, this doesn't need to be virtual. It depends on
// AllInterfaces for its implementation, so it will pick up all changes to MakeAllInterfaces
// indirectly.
private static MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> MakeInterfacesAndTheirBaseInterfaces(ImmutableArray<NamedTypeSymbol> declaredInterfaces)
{
var resultBuilder = new MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>(declaredInterfaces.Length, SymbolEqualityComparer.CLRSignature, SymbolEqualityComparer.ConsiderEverything);
foreach (var @interface in declaredInterfaces)
{
if (resultBuilder.Add(@interface, @interface))
{
foreach (var baseInterface in @interface.AllInterfacesNoUseSiteDiagnostics)
{
resultBuilder.Add(baseInterface, baseInterface);
}
}
}
return resultBuilder;
}
/// <summary>
/// Returns the corresponding symbol in this type or a base type that implements
/// interfaceMember (either implicitly or explicitly), or null if no such symbol exists
/// (which might be either because this type doesn't implement the container of
/// interfaceMember, or this type doesn't supply a member that successfully implements
/// interfaceMember).
/// </summary>
/// <param name="interfaceMember">
/// Must be a non-null interface property, method, or event.
/// </param>
public Symbol FindImplementationForInterfaceMember(Symbol interfaceMember)
{
if ((object)interfaceMember == null)
{
throw new ArgumentNullException(nameof(interfaceMember));
}
if (!interfaceMember.IsImplementableInterfaceMember())
{
return null;
}
if (this.IsInterfaceType())
{
if (interfaceMember.IsStatic)
{
return null;
}
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return FindMostSpecificImplementation(interfaceMember, (NamedTypeSymbol)this, ref discardedUseSiteInfo);
}
return FindImplementationForInterfaceMemberInNonInterface(interfaceMember);
}
/// <summary>
/// Returns true if this type is known to be a reference type. It is never the case that
/// IsReferenceType and IsValueType both return true. However, for an unconstrained type
/// parameter, IsReferenceType and IsValueType will both return false.
/// </summary>
public abstract bool IsReferenceType { get; }
/// <summary>
/// Returns true if this type is known to be a value type. It is never the case that
/// IsReferenceType and IsValueType both return true. However, for an unconstrained type
/// parameter, IsReferenceType and IsValueType will both return false.
/// </summary>
public abstract bool IsValueType { get; }
// Only the compiler can create TypeSymbols.
internal TypeSymbol()
{
}
/// <summary>
/// Gets the kind of this type.
/// </summary>
public abstract TypeKind TypeKind { get; }
/// <summary>
/// Gets corresponding special TypeId of this type.
/// </summary>
/// <remarks>
/// Not preserved in types constructed from this one.
/// </remarks>
public virtual SpecialType SpecialType
{
get
{
return SpecialType.None;
}
}
/// <summary>
/// Gets corresponding primitive type code for this type declaration.
/// </summary>
internal Microsoft.Cci.PrimitiveTypeCode PrimitiveTypeCode
=> TypeKind switch
{
TypeKind.Pointer => Microsoft.Cci.PrimitiveTypeCode.Pointer,
TypeKind.FunctionPointer => Microsoft.Cci.PrimitiveTypeCode.FunctionPointer,
_ => SpecialTypes.GetTypeCode(SpecialType)
};
#region Use-Site Diagnostics
/// <summary>
/// Return error code that has highest priority while calculating use site error for this symbol.
/// </summary>
protected override int HighestPriorityUseSiteError
{
get
{
return (int)ErrorCode.ERR_BogusType;
}
}
public sealed override bool HasUnsupportedMetadata
{
get
{
DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo;
return (object)info != null && info.Code == (int)ErrorCode.ERR_BogusType;
}
}
internal abstract bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes);
#endregion
/// <summary>
/// Is this a symbol for an anonymous type (including delegate).
/// </summary>
public virtual bool IsAnonymousType
{
get
{
return false;
}
}
/// <summary>
/// Is this a symbol for a Tuple.
/// </summary>
public virtual bool IsTupleType => false;
/// <summary>
/// True if the type represents a native integer. In C#, the types represented
/// by language keywords 'nint' and 'nuint'.
/// </summary>
internal virtual bool IsNativeIntegerType => false;
/// <summary>
/// Verify if the given type is a tuple of a given cardinality, or can be used to back a tuple type
/// with the given cardinality.
/// </summary>
internal bool IsTupleTypeOfCardinality(int targetCardinality)
{
if (IsTupleType)
{
return TupleElementTypesWithAnnotations.Length == targetCardinality;
}
return false;
}
/// <summary>
/// If this symbol represents a tuple type, get the types of the tuple's elements.
/// </summary>
public virtual ImmutableArray<TypeWithAnnotations> TupleElementTypesWithAnnotations => default(ImmutableArray<TypeWithAnnotations>);
/// <summary>
/// If this symbol represents a tuple type, get the names of the tuple's elements.
/// </summary>
public virtual ImmutableArray<string> TupleElementNames => default(ImmutableArray<string>);
/// <summary>
/// If this symbol represents a tuple type, get the fields for the tuple's elements.
/// Otherwise, returns default.
/// </summary>
public virtual ImmutableArray<FieldSymbol> TupleElements => default(ImmutableArray<FieldSymbol>);
#nullable enable
/// <summary>
/// Is this type a managed type (false for everything but enum, pointer, and
/// some struct types).
/// </summary>
/// <remarks>
/// See Type::computeManagedType.
/// </remarks>
internal bool IsManagedType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => GetManagedKind(ref useSiteInfo) == ManagedKind.Managed;
internal bool IsManagedTypeNoUseSiteDiagnostics
{
get
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return IsManagedType(ref discardedUseSiteInfo);
}
}
/// <summary>
/// Indicates whether a type is managed or not (i.e. you can take a pointer to it).
/// Contains additional cases to help implement FeatureNotAvailable diagnostics.
/// </summary>
internal abstract ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo);
internal ManagedKind ManagedKindNoUseSiteDiagnostics
{
get
{
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
return GetManagedKind(ref discardedUseSiteInfo);
}
}
#nullable disable
internal bool NeedsNullableAttribute()
{
return TypeWithAnnotations.NeedsNullableAttribute(typeWithAnnotationsOpt: default, typeOpt: this);
}
internal abstract void AddNullableTransforms(ArrayBuilder<byte> transforms);
internal abstract bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result);
internal abstract TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform);
internal TypeSymbol SetUnknownNullabilityForReferenceTypes()
{
return SetNullabilityForReferenceTypes(s_setUnknownNullability);
}
private static readonly Func<TypeWithAnnotations, TypeWithAnnotations> s_setUnknownNullability =
(type) => type.SetUnknownNullabilityForReferenceTypes();
/// <summary>
/// Merges features of the type with another type where there is an identity conversion between them.
/// The features to be merged are
/// object vs dynamic (dynamic wins), tuple names (dropped in case of conflict), and nullable
/// annotations (e.g. in type arguments).
/// </summary>
internal abstract TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance);
/// <summary>
/// Returns true if the type may contain embedded references
/// </summary>
public abstract bool IsRefLikeType { get; }
/// <summary>
/// Returns true if the type is a readonly struct
/// </summary>
public abstract bool IsReadOnly { get; }
public string ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToDisplayString((ITypeSymbol)ISymbol, topLevelNullability, format);
}
public ImmutableArray<SymbolDisplayPart> ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, format);
}
public string ToMinimalDisplayString(
SemanticModel semanticModel,
CodeAnalysis.NullableFlowState topLevelNullability,
int position,
SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToMinimalDisplayString((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format);
}
public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(
SemanticModel semanticModel,
CodeAnalysis.NullableFlowState topLevelNullability,
int position,
SymbolDisplayFormat format = null)
{
return SymbolDisplay.ToMinimalDisplayParts((ITypeSymbol)ISymbol, topLevelNullability, semanticModel, position, format);
}
#region Interface member checks
/// <summary>
/// Locate implementation of the <paramref name="interfaceMember"/> in context of the current type.
/// The method is using cache to optimize subsequent calls for the same <paramref name="interfaceMember"/>.
/// </summary>
/// <param name="interfaceMember">Member for which an implementation should be found.</param>
/// <param name="ignoreImplementationInInterfacesIfResultIsNotReady">
/// The process of looking up an implementation for an accessor can involve figuring out how corresponding event/property is implemented,
/// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. And the process of looking up an implementation for a property can
/// involve figuring out how corresponding accessors are implemented, <see cref="FindMostSpecificImplementationInInterfaces"/>. This can
/// lead to cycles, which could be avoided if we ignore the presence of implementations in interfaces for the purpose of
/// <see cref="CheckForImplementationOfCorrespondingPropertyOrEvent"/>. Fortunately, logic in it allows us to ignore the presence of
/// implementations in interfaces and we use that.
/// When the value of this parameter is true and the result that takes presence of implementations in interfaces into account is not
/// available from the cache, the lookup will be performed ignoring the presence of implementations in interfaces. Otherwise, result from
/// the cache is returned.
/// When the value of the parameter is false, the result from the cache is returned, or calculated, taking presence of implementations
/// in interfaces into account and then cached.
/// This means that:
/// - A symbol from an interface can still be returned even when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true.
/// A subsequent call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value.
/// - If symbol from a non-interface is returned when <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> is true. A subsequent
/// call with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false will return the same value.
/// - If no symbol is returned for <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> true. A subsequent call with
/// <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> might return a symbol, but that symbol guaranteed to be from an interface.
/// - If the first request is done with <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> false. A subsequent call
/// is guaranteed to return the same result regardless of <paramref name="ignoreImplementationInInterfacesIfResultIsNotReady"/> value.
/// </param>
internal SymbolAndDiagnostics FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false)
{
Debug.Assert((object)interfaceMember != null);
Debug.Assert(!this.IsInterfaceType());
if (this.IsInterfaceType())
{
return SymbolAndDiagnostics.Empty;
}
var interfaceType = interfaceMember.ContainingType;
if ((object)interfaceType == null || !interfaceType.IsInterface)
{
return SymbolAndDiagnostics.Empty;
}
switch (interfaceMember.Kind)
{
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
return SymbolAndDiagnostics.Empty;
}
// PERF: Avoid delegate allocation by splitting GetOrAdd into TryGetValue+TryAdd
var map = info.ImplementationForInterfaceMemberMap;
SymbolAndDiagnostics result;
if (map.TryGetValue(interfaceMember, out result))
{
return result;
}
result = ComputeImplementationAndDiagnosticsForInterfaceMember(interfaceMember, ignoreImplementationInInterfaces: ignoreImplementationInInterfacesIfResultIsNotReady,
out bool implementationInInterfacesMightChangeResult);
Debug.Assert(ignoreImplementationInInterfacesIfResultIsNotReady || !implementationInInterfacesMightChangeResult);
Debug.Assert(!implementationInInterfacesMightChangeResult || result.Symbol is null);
if (!implementationInInterfacesMightChangeResult)
{
map.TryAdd(interfaceMember, result);
}
return result;
default:
return SymbolAndDiagnostics.Empty;
}
}
internal Symbol FindImplementationForInterfaceMemberInNonInterface(Symbol interfaceMember, bool ignoreImplementationInInterfacesIfResultIsNotReady = false)
{
return FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember, ignoreImplementationInInterfacesIfResultIsNotReady).Symbol;
}
private SymbolAndDiagnostics ComputeImplementationAndDiagnosticsForInterfaceMember(Symbol interfaceMember, bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult)
{
var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: this.DeclaringCompilation is object);
var implementingMember = ComputeImplementationForInterfaceMember(interfaceMember, this, diagnostics, ignoreImplementationInInterfaces, out implementationInInterfacesMightChangeResult);
var implementingMemberAndDiagnostics = new SymbolAndDiagnostics(implementingMember, diagnostics.ToReadOnlyAndFree());
return implementingMemberAndDiagnostics;
}
/// <summary>
/// Performs interface mapping (spec 13.4.4).
/// </summary>
/// <remarks>
/// CONSIDER: we could probably do less work in the metadata and retargeting cases - we won't use the diagnostics.
/// </remarks>
/// <param name="interfaceMember">A non-null implementable member on an interface type.</param>
/// <param name="implementingType">The type implementing the interface property (usually "this").</param>
/// <param name="diagnostics">Bag to which to add diagnostics.</param>
/// <param name="ignoreImplementationInInterfaces">Do not consider implementation in an interface as a valid candidate for the purpose of this computation.</param>
/// <param name="implementationInInterfacesMightChangeResult">
/// Returns true when <paramref name="ignoreImplementationInInterfaces"/> is true, the method fails to locate an implementation and an implementation in
/// an interface, if any (its presence is not checked), could potentially be a candidate. Returns false otherwise.
/// When true is returned, a different call with <paramref name="ignoreImplementationInInterfaces"/> false might return a symbol. That symbol, if any,
/// is guaranteed to be from an interface.
/// This parameter is used to optimize caching in <see cref="FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics"/>.
/// </param>
/// <returns>The implementing property or null, if there isn't one.</returns>
private static Symbol ComputeImplementationForInterfaceMember(Symbol interfaceMember, TypeSymbol implementingType, BindingDiagnosticBag diagnostics,
bool ignoreImplementationInInterfaces, out bool implementationInInterfacesMightChangeResult)
{
Debug.Assert(!implementingType.IsInterfaceType());
Debug.Assert(interfaceMember.Kind == SymbolKind.Method || interfaceMember.Kind == SymbolKind.Property || interfaceMember.Kind == SymbolKind.Event);
Debug.Assert(interfaceMember.IsImplementableInterfaceMember());
NamedTypeSymbol interfaceType = interfaceMember.ContainingType;
Debug.Assert((object)interfaceType != null && interfaceType.IsInterface);
bool seenTypeDeclaringInterface = false;
// NOTE: In other areas of the compiler, we check whether the member is from a specific compilation.
// We could do the same thing here, but that would mean that callers of the public API would have
// to pass in a Compilation object when asking about interface implementation. This extra cost eliminates
// the small benefit of getting identical answers from "imported" symbols, regardless of whether they
// are imported as source or metadata symbols.
//
// ACASEY: As of 2013/01/24, we are not aware of any cases where the source and metadata behaviors
// disagree *in code that can be emitted*. (If there are any, they are likely to involved ambiguous
// overrides, which typically arise through combinations of ref/out and generics.) In incorrect code,
// the source behavior is somewhat more generous (e.g. accepting a method with the wrong return type),
// but we do not guarantee that incorrect source will be treated in the same way as incorrect metadata.
//
// NOTE: The batch compiler is not affected by this discrepancy, since compilations don't call these
// APIs on symbols from other compilations.
bool implementingTypeIsFromSomeCompilation = false;
Symbol implicitImpl = null;
Symbol closestMismatch = null;
bool canBeImplementedImplicitlyInCSharp9 = interfaceMember.DeclaredAccessibility == Accessibility.Public && !interfaceMember.IsEventOrPropertyWithImplementableNonPublicAccessor();
TypeSymbol implementingBaseOpt = null; // Calculated only if canBeImplementedImplicitly == false
bool implementingTypeImplementsInterface = false;
CSharpCompilation compilation = implementingType.DeclaringCompilation;
var useSiteInfo = compilation is object ? new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies;
for (TypeSymbol currType = implementingType; (object)currType != null; currType = currType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo))
{
// NOTE: In the case of PE symbols, it is possible to see an explicit implementation
// on a type that does not declare the corresponding interface (or one of its
// subinterfaces). In such cases, we want to return the explicit implementation,
// even if it doesn't participate in interface mapping according to the C# rules.
// pass 1: check for explicit impls (can't assume name matches)
MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = currType.GetExplicitImplementationForInterfaceMember(interfaceMember);
if (explicitImpl.Count == 1)
{
implementationInInterfacesMightChangeResult = false;
return explicitImpl.Single();
}
else if (explicitImpl.Count > 1)
{
if ((object)currType == implementingType || implementingTypeImplementsInterface)
{
diagnostics.Add(ErrorCode.ERR_DuplicateExplicitImpl, implementingType.Locations[0], interfaceMember);
}
implementationInInterfacesMightChangeResult = false;
return null;
}
bool checkPendingExplicitImplementations = ((object)currType != implementingType || !currType.IsDefinition);
if (checkPendingExplicitImplementations && interfaceMember is MethodSymbol interfaceMethod &&
currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType))
{
// Check for implementations that are going to be explicit once types are emitted
MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceMethod);
if (bodyOfSynthesizedMethodImpl is object)
{
implementationInInterfacesMightChangeResult = false;
return bodyOfSynthesizedMethodImpl;
}
}
if (IsExplicitlyImplementedViaAccessors(checkPendingExplicitImplementations, interfaceMember, currType, ref useSiteInfo, out Symbol currTypeExplicitImpl))
{
// We are looking for a property or event implementation and found an explicit implementation
// for its accessor(s) in this type. Stop the process and return event/property associated
// with the accessor(s), if any.
implementationInInterfacesMightChangeResult = false;
// NOTE: may be null.
return currTypeExplicitImpl;
}
if (!seenTypeDeclaringInterface ||
(!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null))
{
if (currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceType))
{
if (!seenTypeDeclaringInterface)
{
implementingTypeIsFromSomeCompilation = currType.OriginalDefinition.ContainingModule is not PEModuleSymbol;
seenTypeDeclaringInterface = true;
}
if ((object)currType == implementingType)
{
implementingTypeImplementsInterface = true;
}
else if (!canBeImplementedImplicitlyInCSharp9 && (object)implementingBaseOpt == null)
{
implementingBaseOpt = currType;
}
}
}
// We want the implementation from the most derived type at or above the first one to
// include the interface (or a subinterface) in its interface list
if (seenTypeDeclaringInterface &&
(!interfaceMember.IsStatic || implementingTypeIsFromSomeCompilation))
{
//pass 2: check for implicit impls (name must match)
Symbol currTypeImplicitImpl;
Symbol currTypeCloseMismatch;
FindPotentialImplicitImplementationMemberDeclaredInType(
interfaceMember,
implementingTypeIsFromSomeCompilation,
currType,
out currTypeImplicitImpl,
out currTypeCloseMismatch);
if ((object)currTypeImplicitImpl != null)
{
implicitImpl = currTypeImplicitImpl;
break;
}
if ((object)closestMismatch == null)
{
closestMismatch = currTypeCloseMismatch;
}
}
}
Debug.Assert(!canBeImplementedImplicitlyInCSharp9 || (object)implementingBaseOpt == null);
bool tryDefaultInterfaceImplementation = !interfaceMember.IsStatic;
// Dev10 has some extra restrictions and extra wiggle room when finding implicit
// implementations for interface accessors. Perform some extra checks and possibly
// update the result (i.e. implicitImpl).
if (interfaceMember.IsAccessor())
{
Symbol originalImplicitImpl = implicitImpl;
CheckForImplementationOfCorrespondingPropertyOrEvent((MethodSymbol)interfaceMember, implementingType, implementingTypeIsFromSomeCompilation, ref implicitImpl);
// If we discarded the candidate, we don't want default interface implementation to take over later, since runtime might still use the discarded candidate.
if (originalImplicitImpl is object && implicitImpl is null)
{
tryDefaultInterfaceImplementation = false;
}
}
Symbol defaultImpl = null;
if ((object)implicitImpl == null && seenTypeDeclaringInterface && tryDefaultInterfaceImplementation)
{
if (ignoreImplementationInInterfaces)
{
implementationInInterfacesMightChangeResult = true;
}
else
{
// Check for default interface implementations
defaultImpl = FindMostSpecificImplementationInInterfaces(interfaceMember, implementingType, ref useSiteInfo, diagnostics);
implementationInInterfacesMightChangeResult = false;
}
}
else
{
implementationInInterfacesMightChangeResult = false;
}
diagnostics.Add(
#if !DEBUG
// Don't optimize in DEBUG for better coverage for the GetInterfaceLocation function.
useSiteInfo.Diagnostics is null || !implementingTypeImplementsInterface ? Location.None :
#endif
GetInterfaceLocation(interfaceMember, implementingType),
useSiteInfo);
if (defaultImpl is object)
{
if (implementingTypeImplementsInterface)
{
ReportDefaultInterfaceImplementationMatchDiagnostics(interfaceMember, implementingType, defaultImpl, diagnostics);
}
return defaultImpl;
}
if (implementingTypeImplementsInterface)
{
if ((object)implicitImpl != null)
{
if (!canBeImplementedImplicitlyInCSharp9)
{
if (interfaceMember.Kind == SymbolKind.Method &&
(object)implementingBaseOpt == null) // Otherwise any approprite errors are going to be reported for the base.
{
LanguageVersion requiredVersion = MessageID.IDS_FeatureImplicitImplementationOfNonPublicMembers.RequiredVersion();
LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion;
if (requiredVersion > availableVersion)
{
diagnostics.Add(ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember, GetInterfaceLocation(interfaceMember, implementingType),
implementingType, interfaceMember, implicitImpl,
availableVersion.GetValueOrDefault().ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion));
}
}
}
ReportImplicitImplementationMatchDiagnostics(interfaceMember, implementingType, implicitImpl, diagnostics);
}
else if ((object)closestMismatch != null)
{
ReportImplicitImplementationMismatchDiagnostics(interfaceMember, implementingType, closestMismatch, diagnostics);
}
}
return implicitImpl;
}
private static Symbol FindMostSpecificImplementationInInterfaces(Symbol interfaceMember, TypeSymbol implementingType,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
BindingDiagnosticBag diagnostics)
{
Debug.Assert(!implementingType.IsInterfaceType());
Debug.Assert(!interfaceMember.IsStatic);
// If we are dealing with a property or event and an implementation of at least one accessor is not from an interface, it
// wouldn't be right to say that the event/property is implemented in an interface because its accessor isn't.
(MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember);
if (stopLookup(interfaceAccessor1, implementingType) || stopLookup(interfaceAccessor2, implementingType))
{
return null;
}
Symbol defaultImpl = FindMostSpecificImplementationInBases(interfaceMember,
implementingType,
ref useSiteInfo, out Symbol conflict1, out Symbol conflict2);
if ((object)conflict1 != null)
{
Debug.Assert((object)defaultImpl == null);
Debug.Assert((object)conflict2 != null);
diagnostics.Add(ErrorCode.ERR_MostSpecificImplementationIsNotFound, GetInterfaceLocation(interfaceMember, implementingType),
interfaceMember, conflict1, conflict2);
}
else
{
Debug.Assert(((object)conflict2 == null));
}
return defaultImpl;
static bool stopLookup(MethodSymbol interfaceAccessor, TypeSymbol implementingType)
{
if (interfaceAccessor is null)
{
return false;
}
SymbolAndDiagnostics symbolAndDiagnostics = implementingType.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceAccessor);
if (symbolAndDiagnostics.Symbol is object)
{
return !symbolAndDiagnostics.Symbol.ContainingType.IsInterface;
}
// It is still possible that we actually looked for the accessor in interfaces, but failed due to an ambiguity.
// Let's try to look for a property to improve diagnostics in this scenario.
return !symbolAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Code == (int)ErrorCode.ERR_MostSpecificImplementationIsNotFound);
}
}
private static Symbol FindMostSpecificImplementation(Symbol interfaceMember, NamedTypeSymbol implementingInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface);
switch (implementingMember.Count)
{
case 0:
(MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember);
// If interface actually implements an event or property accessor, but doesn't implement the event/property,
// do not look for its implementation in bases.
if ((interfaceAccessor1 is object && FindImplementationInInterface(interfaceAccessor1, implementingInterface).Count != 0) ||
(interfaceAccessor2 is object && FindImplementationInInterface(interfaceAccessor2, implementingInterface).Count != 0))
{
return null;
}
return FindMostSpecificImplementationInBases(interfaceMember, implementingInterface,
ref useSiteInfo,
out var _, out var _);
case 1:
{
Symbol result = implementingMember.Single();
if (result.IsAbstract)
{
return null;
}
return result;
}
default:
return null;
}
}
/// <summary>
/// One implementation M1 is considered more specific than another implementation M2
/// if M1 is declared on interface T1, M2 is declared on interface T2, and
/// T1 contains T2 among its direct or indirect interfaces.
/// </summary>
private static Symbol FindMostSpecificImplementationInBases(
Symbol interfaceMember,
TypeSymbol implementingType,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
out Symbol conflictingImplementation1,
out Symbol conflictingImplementation2)
{
ImmutableArray<NamedTypeSymbol> allInterfaces = implementingType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
if (allInterfaces.IsEmpty)
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
return null;
}
// Properties or events can be implemented in an unconventional manner, i.e. implementing accessors might not be tied to a property/event.
// If we simply look for a more specific implementing property/event, we might find one with not most specific implementing accessors.
// Returning a property/event like that would be incorrect because runtime will use most specific accessor, or it will fail because there will
// be an ambiguity for the accessor implementation.
// So, for events and properties we look for most specific implementation of corresponding accessors and then try to tie them back to
// an event/property, if any.
(MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember);
if (interfaceAccessor1 is null && interfaceAccessor2 is null)
{
return findMostSpecificImplementationInBases(interfaceMember, allInterfaces, ref useSiteInfo, out conflictingImplementation1, out conflictingImplementation2);
}
Symbol accessorImpl1 = findMostSpecificImplementationInBases(interfaceAccessor1 ?? interfaceAccessor2, allInterfaces, ref useSiteInfo,
out Symbol conflictingAccessorImplementation11, out Symbol conflictingAccessorImplementation12);
if (accessorImpl1 is null && conflictingAccessorImplementation11 is null) // implementation of accessor is not found
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
return null;
}
if (interfaceAccessor1 is null || interfaceAccessor2 is null)
{
if (accessorImpl1 is object)
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
return findImplementationInInterface(interfaceMember, accessorImpl1);
}
conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11);
conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12);
if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null))
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
}
return null;
}
Symbol accessorImpl2 = findMostSpecificImplementationInBases(interfaceAccessor2, allInterfaces, ref useSiteInfo,
out Symbol conflictingAccessorImplementation21, out Symbol conflictingAccessorImplementation22);
if ((accessorImpl2 is null && conflictingAccessorImplementation21 is null) || // implementation of accessor is not found
(accessorImpl1 is null) != (accessorImpl2 is null)) // there is most specific implementation for one accessor and an ambiguous implementation for the other accessor.
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
return null;
}
if (accessorImpl1 is object)
{
conflictingImplementation1 = null;
conflictingImplementation2 = null;
return findImplementationInInterface(interfaceMember, accessorImpl1, accessorImpl2);
}
conflictingImplementation1 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation11, conflictingAccessorImplementation21);
conflictingImplementation2 = findImplementationInInterface(interfaceMember, conflictingAccessorImplementation12, conflictingAccessorImplementation22);
if ((conflictingImplementation1 is null) != (conflictingImplementation2 is null))
{
// One pair of conflicting accessors can be tied to an event/property, but the other cannot be tied to an event/property.
// Dropping conflict information since it only affects diagnostic.
conflictingImplementation1 = null;
conflictingImplementation2 = null;
}
return null;
static Symbol findImplementationInInterface(Symbol interfaceMember, Symbol inplementingAccessor1, Symbol implementingAccessor2 = null)
{
NamedTypeSymbol implementingInterface = inplementingAccessor1.ContainingType;
if (implementingAccessor2 is object && !implementingInterface.Equals(implementingAccessor2.ContainingType, TypeCompareKind.ConsiderEverything))
{
// Implementing accessors are from different types, they cannot be tied to the same event/property.
return null;
}
MultiDictionary<Symbol, Symbol>.ValueSet implementingMember = FindImplementationInInterface(interfaceMember, implementingInterface);
switch (implementingMember.Count)
{
case 1:
return implementingMember.Single();
default:
return null;
}
}
static Symbol findMostSpecificImplementationInBases(
Symbol interfaceMember,
ImmutableArray<NamedTypeSymbol> allInterfaces,
ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo,
out Symbol conflictingImplementation1,
out Symbol conflictingImplementation2)
{
var implementations = ArrayBuilder<(MultiDictionary<Symbol, Symbol>.ValueSet MethodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> Bases)>.GetInstance();
foreach (var interfaceType in allInterfaces)
{
if (!interfaceType.IsInterface)
{
// this code is reachable in error situations
continue;
}
MultiDictionary<Symbol, Symbol>.ValueSet candidate = FindImplementationInInterface(interfaceMember, interfaceType);
if (candidate.Count == 0)
{
continue;
}
for (int i = 0; i < implementations.Count; i++)
{
(MultiDictionary<Symbol, Symbol>.ValueSet methodSet, MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases) = implementations[i];
Symbol previous = methodSet.First();
NamedTypeSymbol previousContainingType = previous.ContainingType;
if (previousContainingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions))
{
// Last equivalent match wins
implementations[i] = (candidate, bases);
candidate = default;
break;
}
if (bases == null)
{
Debug.Assert(implementations.Count == 1);
bases = previousContainingType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
implementations[i] = (methodSet, bases);
}
if (bases.ContainsKey(interfaceType))
{
// Previous candidate is more specific
candidate = default;
break;
}
}
if (candidate.Count == 0)
{
continue;
}
if (implementations.Count != 0)
{
MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> bases = interfaceType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo);
for (int i = implementations.Count - 1; i >= 0; i--)
{
if (bases.ContainsKey(implementations[i].MethodSet.First().ContainingType))
{
// new candidate is more specific
implementations.RemoveAt(i);
}
}
implementations.Add((candidate, bases));
}
else
{
implementations.Add((candidate, null));
}
}
Symbol result;
switch (implementations.Count)
{
case 0:
result = null;
conflictingImplementation1 = null;
conflictingImplementation2 = null;
break;
case 1:
MultiDictionary<Symbol, Symbol>.ValueSet methodSet = implementations[0].MethodSet;
switch (methodSet.Count)
{
case 1:
result = methodSet.Single();
if (result.IsAbstract)
{
result = null;
}
break;
default:
result = null;
break;
}
conflictingImplementation1 = null;
conflictingImplementation2 = null;
break;
default:
result = null;
conflictingImplementation1 = implementations[0].MethodSet.First();
conflictingImplementation2 = implementations[1].MethodSet.First();
break;
}
implementations.Free();
return result;
}
}
internal static MultiDictionary<Symbol, Symbol>.ValueSet FindImplementationInInterface(Symbol interfaceMember, NamedTypeSymbol interfaceType)
{
Debug.Assert(interfaceType.IsInterface);
Debug.Assert(!interfaceMember.IsStatic);
NamedTypeSymbol containingType = interfaceMember.ContainingType;
if (containingType.Equals(interfaceType, TypeCompareKind.CLRSignatureCompareOptions))
{
if (!interfaceMember.IsAbstract)
{
if (!containingType.Equals(interfaceType, TypeCompareKind.ConsiderEverything))
{
interfaceMember = interfaceMember.OriginalDefinition.SymbolAsMember(interfaceType);
}
return new MultiDictionary<Symbol, Symbol>.ValueSet(interfaceMember);
}
return default;
}
return interfaceType.GetExplicitImplementationForInterfaceMember(interfaceMember);
}
private static (MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) GetImplementableAccessors(Symbol interfaceMember)
{
MethodSymbol interfaceAccessor1;
MethodSymbol interfaceAccessor2;
switch (interfaceMember.Kind)
{
case SymbolKind.Property:
{
PropertySymbol interfaceProperty = (PropertySymbol)interfaceMember;
interfaceAccessor1 = interfaceProperty.GetMethod;
interfaceAccessor2 = interfaceProperty.SetMethod;
break;
}
case SymbolKind.Event:
{
EventSymbol interfaceEvent = (EventSymbol)interfaceMember;
interfaceAccessor1 = interfaceEvent.AddMethod;
interfaceAccessor2 = interfaceEvent.RemoveMethod;
break;
}
default:
{
interfaceAccessor1 = null;
interfaceAccessor2 = null;
break;
}
}
if (!interfaceAccessor1.IsImplementable())
{
interfaceAccessor1 = null;
}
if (!interfaceAccessor2.IsImplementable())
{
interfaceAccessor2 = null;
}
return (interfaceAccessor1, interfaceAccessor2);
}
/// <summary>
/// Since dev11 didn't expose a symbol API, it had the luxury of being able to accept a base class's claim that
/// it implements an interface. Roslyn, on the other hand, needs to be able to point to an implementing symbol
/// for each interface member.
///
/// DevDiv #718115 was triggered by some unusual metadata in a Microsoft reference assembly (Silverlight System.Windows.dll).
/// The issue was that a type explicitly implemented the accessors of an interface event, but did not tie them together with
/// an event declaration. To make matters worse, it declared its own protected event with the same name as the interface
/// event (presumably to back the explicit implementation). As a result, when Roslyn was asked to find the implementing member
/// for the interface event, it found the protected event and reported an appropriate diagnostic. What it should have done
/// (and does do now) is recognize that no event associated with the accessors explicitly implementing the interface accessors
/// and returned null.
///
/// We resolved this issue by introducing a new step into the interface mapping algorithm: after failing to find an explicit
/// implementation in a type, but before searching for an implicit implementation in that type, check for an explicit implementation
/// of an associated accessor. If there is such an implementation, then immediately return the associated property or event,
/// even if it is null. That is, never attempt to find an implicit implementation for an interface property or event with an
/// explicitly implemented accessor.
/// </summary>
private static bool IsExplicitlyImplementedViaAccessors(bool checkPendingExplicitImplementations, Symbol interfaceMember, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol implementingMember)
{
(MethodSymbol interfaceAccessor1, MethodSymbol interfaceAccessor2) = GetImplementableAccessors(interfaceMember);
Symbol associated1;
Symbol associated2;
if (TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor1, currType, ref useSiteInfo, out associated1) | // NB: not ||
TryGetExplicitImplementationAssociatedPropertyOrEvent(checkPendingExplicitImplementations, interfaceAccessor2, currType, ref useSiteInfo, out associated2))
{
// If there's more than one associated property/event, don't do anything special - just let the algorithm
// fail in the usual way.
if ((object)associated1 == null || (object)associated2 == null || associated1 == associated2)
{
implementingMember = associated1 ?? associated2;
// In source, we should already have seen an explicit implementation for the interface property/event.
// If we haven't then there is no implementation. We need this check to match dev11 in some edge cases
// (e.g. IndexerTests.AmbiguousExplicitIndexerImplementation). Such cases already fail
// to roundtrip correctly, so it's not important to check for a particular compilation.
if ((object)implementingMember != null && implementingMember.OriginalDefinition.ContainingModule is not PEModuleSymbol && implementingMember.IsExplicitInterfaceImplementation())
{
implementingMember = null;
}
}
else
{
implementingMember = null;
}
return true;
}
implementingMember = null;
return false;
}
private static bool TryGetExplicitImplementationAssociatedPropertyOrEvent(bool checkPendingExplicitImplementations, MethodSymbol interfaceAccessor, TypeSymbol currType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out Symbol associated)
{
if ((object)interfaceAccessor != null)
{
// NB: uses a map that was built (and saved) when we checked for an explicit
// implementation of the interface member.
MultiDictionary<Symbol, Symbol>.ValueSet set = currType.GetExplicitImplementationForInterfaceMember(interfaceAccessor);
if (set.Count == 1)
{
Symbol implementation = set.Single();
associated = implementation.Kind == SymbolKind.Method
? ((MethodSymbol)implementation).AssociatedSymbol
: null;
return true;
}
if (checkPendingExplicitImplementations &&
currType.InterfacesAndTheirBaseInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo).ContainsKey(interfaceAccessor.ContainingType))
{
// Check for implementations that are going to be explicit once types are emitted
MethodSymbol bodyOfSynthesizedMethodImpl = currType.GetBodyOfSynthesizedInterfaceMethodImpl(interfaceAccessor);
if (bodyOfSynthesizedMethodImpl is object)
{
associated = bodyOfSynthesizedMethodImpl.AssociatedSymbol;
return true;
}
}
}
associated = null;
return false;
}
/// <summary>
/// If we were looking for an accessor, then look for an accessor on the implementation of the
/// corresponding interface property/event. If it is valid as an implementation (ignoring the name),
/// then prefer it to our current result if:
/// 1) our current result is null; or
/// 2) our current result is on the same type.
///
/// If there is no corresponding accessor on the implementation of the corresponding interface
/// property/event and we found an accessor, then the accessor we found is invalid, so clear it.
/// </summary>
private static void CheckForImplementationOfCorrespondingPropertyOrEvent(MethodSymbol interfaceMethod, TypeSymbol implementingType, bool implementingTypeIsFromSomeCompilation,
ref Symbol implicitImpl)
{
Debug.Assert(!implementingType.IsInterfaceType());
Debug.Assert(interfaceMethod.IsAccessor());
Symbol associatedInterfacePropertyOrEvent = interfaceMethod.AssociatedSymbol;
// Do not make any adjustments based on presence of default interface implementation for the property or event.
// We don't want an addition of default interface implementation to change an error situation to success for
// scenarios where the default interface implementation wouldn't actually be used at runtime.
// When we find an implicit implementation candidate, we don't want to not discard it if we would discard it when
// default interface implementation was missing. Why would presence of default interface implementation suddenly
// make the candidate suiatable to implement the interface? Also, if we discard the candidate, we don't want default interface
// implementation to take over later, since runtime might still use the discarded candidate.
// When we don't find any implicit implementation candidate, returning accessor of default interface implementation
// doesn't actually help much because we would find it anyway (it is implemented explicitly).
Symbol implementingPropertyOrEvent = implementingType.FindImplementationForInterfaceMemberInNonInterface(associatedInterfacePropertyOrEvent,
ignoreImplementationInInterfacesIfResultIsNotReady: true); // NB: uses cache
MethodSymbol correspondingImplementingAccessor = null;
if ((object)implementingPropertyOrEvent != null && !implementingPropertyOrEvent.ContainingType.IsInterface)
{
switch (interfaceMethod.MethodKind)
{
case MethodKind.PropertyGet:
correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedGetMethod();
break;
case MethodKind.PropertySet:
correspondingImplementingAccessor = ((PropertySymbol)implementingPropertyOrEvent).GetOwnOrInheritedSetMethod();
break;
case MethodKind.EventAdd:
correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedAddMethod();
break;
case MethodKind.EventRemove:
correspondingImplementingAccessor = ((EventSymbol)implementingPropertyOrEvent).GetOwnOrInheritedRemoveMethod();
break;
default:
throw ExceptionUtilities.UnexpectedValue(interfaceMethod.MethodKind);
}
}
if (correspondingImplementingAccessor == implicitImpl)
{
return;
}
else if ((object)correspondingImplementingAccessor == null && (object)implicitImpl != null && implicitImpl.IsAccessor())
{
// If we found an accessor, but it's not (directly or indirectly) on the property implementation,
// then it's not a valid match.
implicitImpl = null;
}
else if ((object)correspondingImplementingAccessor != null && ((object)implicitImpl == null || TypeSymbol.Equals(correspondingImplementingAccessor.ContainingType, implicitImpl.ContainingType, TypeCompareKind.ConsiderEverything2)))
{
// Suppose the interface accessor and the implementing accessor have different names.
// In Dev10, as long as the corresponding properties have an implementation relationship,
// then the accessor can be considered an implementation, even though the name is different.
// Later on, when we check that implementation signatures match exactly
// (in SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation),
// they won't (because of the names) and an explicit implementation method will be synthesized.
MethodSymbol interfaceAccessorWithImplementationName = new SignatureOnlyMethodSymbol(
correspondingImplementingAccessor.Name,
interfaceMethod.ContainingType,
interfaceMethod.MethodKind,
interfaceMethod.CallingConvention,
interfaceMethod.TypeParameters,
interfaceMethod.Parameters,
interfaceMethod.RefKind,
interfaceMethod.IsInitOnly,
interfaceMethod.IsStatic,
interfaceMethod.ReturnTypeWithAnnotations,
interfaceMethod.RefCustomModifiers,
interfaceMethod.ExplicitInterfaceImplementations);
// Make sure that the corresponding accessor is a real implementation.
if (IsInterfaceMemberImplementation(correspondingImplementingAccessor, interfaceAccessorWithImplementationName, implementingTypeIsFromSomeCompilation))
{
implicitImpl = correspondingImplementingAccessor;
}
}
}
private static void ReportDefaultInterfaceImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics)
{
if (interfaceMember.Kind == SymbolKind.Method && implementingType.ContainingModule != implicitImpl.ContainingModule)
{
// The default implementation is coming from a different module, which means that we probably didn't check
// for the required runtime capability or language version
LanguageVersion requiredVersion = MessageID.IDS_DefaultInterfaceImplementation.RequiredVersion();
LanguageVersion? availableVersion = implementingType.DeclaringCompilation?.LanguageVersion;
if (requiredVersion > availableVersion)
{
diagnostics.Add(ErrorCode.ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember,
GetInterfaceLocation(interfaceMember, implementingType),
implicitImpl, interfaceMember, implementingType,
MessageID.IDS_DefaultInterfaceImplementation.Localize(),
availableVersion.GetValueOrDefault().ToDisplayString(),
new CSharpRequiredLanguageVersion(requiredVersion));
}
if (!implementingType.ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation)
{
diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember,
GetInterfaceLocation(interfaceMember, implementingType),
implicitImpl, interfaceMember, implementingType);
}
}
}
/// <summary>
/// These diagnostics are for members that do implicitly implement an interface member, but do so
/// in an undesirable way.
/// </summary>
private static void ReportImplicitImplementationMatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol implicitImpl, BindingDiagnosticBag diagnostics)
{
bool reportedAnError = false;
if (interfaceMember.Kind == SymbolKind.Method)
{
var interfaceMethod = (MethodSymbol)interfaceMember;
bool implicitImplIsAccessor = implicitImpl.IsAccessor();
bool interfaceMethodIsAccessor = interfaceMethod.IsAccessor();
if (interfaceMethodIsAccessor && !implicitImplIsAccessor && !interfaceMethod.IsIndexedPropertyAccessor())
{
diagnostics.Add(ErrorCode.ERR_MethodImplementingAccessor, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType);
}
else if (!interfaceMethodIsAccessor && implicitImplIsAccessor)
{
diagnostics.Add(ErrorCode.ERR_AccessorImplementingMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType);
}
else
{
var implicitImplMethod = (MethodSymbol)implicitImpl;
if (implicitImplMethod.IsConditional)
{
// CS0629: Conditional member '{0}' cannot implement interface member '{1}' in type '{2}'
diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByConditional, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType);
}
else if (implicitImplMethod.IsStatic && implicitImplMethod.MethodKind == MethodKind.Ordinary && implicitImplMethod.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is not null)
{
diagnostics.Add(ErrorCode.ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMethod, implementingType);
}
else if (ReportAnyMismatchedConstraints(interfaceMethod, implementingType, implicitImplMethod, diagnostics))
{
reportedAnError = true;
}
}
}
if (implicitImpl.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(implicitImpl, interfaceMember))
{
// it is ok to implement implicitly with no tuple names, for compatibility with C# 6, but otherwise names should match
diagnostics.Add(ErrorCode.ERR_ImplBadTupleNames, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, implicitImpl), implicitImpl, interfaceMember);
reportedAnError = true;
}
if (!reportedAnError && implementingType.DeclaringCompilation != null)
{
CheckNullableReferenceTypeMismatchOnImplementingMember(implementingType, implicitImpl, interfaceMember, isExplicit: false, diagnostics);
}
// In constructed types, it is possible to see multiple members with the same (runtime) signature.
// Now that we know which member will implement the interface member, confirm that it is the only
// such member.
if (!implicitImpl.ContainingType.IsDefinition)
{
foreach (Symbol member in implicitImpl.ContainingType.GetMembers(implicitImpl.Name))
{
if (member.DeclaredAccessibility != Accessibility.Public || member.IsStatic || member == implicitImpl)
{
//do nothing - not an ambiguous implementation
}
else if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, member) && !member.IsAccessor())
{
// CONSIDER: Dev10 does not seem to report this for indexers or their accessors.
diagnostics.Add(ErrorCode.WRN_MultipleRuntimeImplementationMatches, GetImplicitImplementationDiagnosticLocation(interfaceMember, implementingType, member), member, interfaceMember, implementingType);
}
}
}
if (implicitImpl.IsStatic && !implementingType.ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces)
{
diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember,
GetInterfaceLocation(interfaceMember, implementingType),
implicitImpl, interfaceMember, implementingType);
}
}
internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(TypeSymbol implementingType, Symbol implementingMember, Symbol interfaceMember, bool isExplicit, BindingDiagnosticBag diagnostics)
{
if (!implementingMember.IsImplicitlyDeclared && !implementingMember.IsAccessor())
{
CSharpCompilation compilation = implementingType.DeclaringCompilation;
if (interfaceMember.Kind == SymbolKind.Event)
{
var implementingEvent = (EventSymbol)implementingMember;
var implementedEvent = (EventSymbol)interfaceMember;
SourceMemberContainerTypeSymbol.CheckValidNullableEventOverride(compilation, implementedEvent, implementingEvent,
diagnostics,
(diagnostics, implementedEvent, implementingEvent, arg) =>
{
if (arg.isExplicit)
{
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation,
implementingEvent.Locations[0], new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
else
{
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation,
GetImplicitImplementationDiagnosticLocation(implementedEvent, arg.implementingType, implementingEvent),
new FormattedSymbol(implementingEvent, SymbolDisplayFormat.MinimallyQualifiedFormat),
new FormattedSymbol(implementedEvent, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
},
(implementingType, isExplicit));
}
else
{
ReportMismatchInReturnType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInReturnType =
(diagnostics, implementedMethod, implementingMethod, topLevel, arg) =>
{
if (arg.isExplicit)
{
// We use ConstructedFrom symbols here and below to not leak methods with Ignored annotations in type arguments
// into diagnostics
diagnostics.Add(topLevel ?
ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation :
ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation,
implementingMethod.Locations[0], new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
else
{
diagnostics.Add(topLevel ?
ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation :
ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation,
GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod),
new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat),
new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
};
ReportMismatchInParameterType<(TypeSymbol implementingType, bool isExplicit)> reportMismatchInParameterType =
(diagnostics, implementedMethod, implementingMethod, implementingParameter, topLevel, arg) =>
{
if (arg.isExplicit)
{
diagnostics.Add(topLevel ?
ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation :
ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation,
implementingMethod.Locations[0],
new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat),
new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
else
{
diagnostics.Add(topLevel ?
ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation :
ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation,
GetImplicitImplementationDiagnosticLocation(implementedMethod, arg.implementingType, implementingMethod),
new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat),
new FormattedSymbol(implementingMethod, SymbolDisplayFormat.MinimallyQualifiedFormat),
new FormattedSymbol(implementedMethod.ConstructedFrom, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
};
switch (interfaceMember.Kind)
{
case SymbolKind.Property:
var implementingProperty = (PropertySymbol)implementingMember;
var implementedProperty = (PropertySymbol)interfaceMember;
if (implementedProperty.GetMethod.IsImplementable())
{
MethodSymbol implementingGetMethod = implementingProperty.GetOwnOrInheritedGetMethod();
SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(
compilation,
implementedProperty.GetMethod,
implementingGetMethod,
diagnostics,
reportMismatchInReturnType,
// Don't check parameters on the getter if there is a setter
// because they will be a subset of the setter
(!implementedProperty.SetMethod.IsImplementable() ||
implementingGetMethod?.AssociatedSymbol != implementingProperty ||
implementingProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != implementingProperty) ? reportMismatchInParameterType : null,
(implementingType, isExplicit));
}
if (implementedProperty.SetMethod.IsImplementable())
{
SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(
compilation,
implementedProperty.SetMethod,
implementingProperty.GetOwnOrInheritedSetMethod(),
diagnostics,
null,
reportMismatchInParameterType,
(implementingType, isExplicit));
}
break;
case SymbolKind.Method:
var implementingMethod = (MethodSymbol)implementingMember;
var implementedMethod = (MethodSymbol)interfaceMember;
if (implementedMethod.IsGenericMethod)
{
implementedMethod = implementedMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementingMethod.TypeParameters));
}
SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(
compilation,
implementedMethod,
implementingMethod,
diagnostics,
reportMismatchInReturnType,
reportMismatchInParameterType,
(implementingType, isExplicit));
break;
default:
throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind);
}
}
}
}
/// <summary>
/// These diagnostics are for members that almost, but not actually, implicitly implement an interface member.
/// </summary>
private static void ReportImplicitImplementationMismatchDiagnostics(Symbol interfaceMember, TypeSymbol implementingType, Symbol closestMismatch, BindingDiagnosticBag diagnostics)
{
// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class.
Location interfaceLocation = GetInterfaceLocation(interfaceMember, implementingType);
if (closestMismatch.IsStatic != interfaceMember.IsStatic)
{
diagnostics.Add(closestMismatch.IsStatic ? ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotStatic,
interfaceLocation, implementingType, interfaceMember, closestMismatch);
}
else if (closestMismatch.DeclaredAccessibility != Accessibility.Public)
{
ErrorCode errorCode = interfaceMember.IsAccessor() ? ErrorCode.ERR_UnimplementedInterfaceAccessor : ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic;
diagnostics.Add(errorCode, interfaceLocation, implementingType, interfaceMember, closestMismatch);
}
else if (HaveInitOnlyMismatch(interfaceMember, closestMismatch))
{
diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, interfaceLocation, implementingType, interfaceMember, closestMismatch);
}
else //return ref kind or type doesn't match
{
RefKind interfaceMemberRefKind = RefKind.None;
TypeSymbol interfaceMemberReturnType;
switch (interfaceMember.Kind)
{
case SymbolKind.Method:
var method = (MethodSymbol)interfaceMember;
interfaceMemberRefKind = method.RefKind;
interfaceMemberReturnType = method.ReturnType;
break;
case SymbolKind.Property:
var property = (PropertySymbol)interfaceMember;
interfaceMemberRefKind = property.RefKind;
interfaceMemberReturnType = property.Type;
break;
case SymbolKind.Event:
interfaceMemberReturnType = ((EventSymbol)interfaceMember).Type;
break;
default:
throw ExceptionUtilities.UnexpectedValue(interfaceMember.Kind);
}
bool hasRefReturnMismatch = false;
switch (closestMismatch.Kind)
{
case SymbolKind.Method:
hasRefReturnMismatch = ((MethodSymbol)closestMismatch).RefKind != interfaceMemberRefKind;
break;
case SymbolKind.Property:
hasRefReturnMismatch = ((PropertySymbol)closestMismatch).RefKind != interfaceMemberRefKind;
break;
}
DiagnosticInfo useSiteDiagnostic;
if ((object)interfaceMemberReturnType != null &&
(useSiteDiagnostic = interfaceMemberReturnType.GetUseSiteInfo().DiagnosticInfo) != null &&
useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error)
{
diagnostics.Add(useSiteDiagnostic, interfaceLocation);
}
else if (hasRefReturnMismatch)
{
diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongRefReturn, interfaceLocation, implementingType, interfaceMember, closestMismatch);
}
else
{
diagnostics.Add(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, interfaceLocation, implementingType, interfaceMember, closestMismatch, interfaceMemberReturnType);
}
}
}
internal static bool HaveInitOnlyMismatch(Symbol one, Symbol other)
{
if (!(one is MethodSymbol oneMethod))
{
return false;
}
if (!(other is MethodSymbol otherMethod))
{
return false;
}
return oneMethod.IsInitOnly != otherMethod.IsInitOnly;
}
/// <summary>
/// Determine a better location for diagnostic squiggles. Squiggle the interface rather than the class.
/// </summary>
private static Location GetInterfaceLocation(Symbol interfaceMember, TypeSymbol implementingType)
{
Debug.Assert((object)implementingType != null);
var @interface = interfaceMember.ContainingType;
SourceMemberContainerTypeSymbol snt = null;
if (implementingType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface].Contains(@interface))
{
snt = implementingType as SourceMemberContainerTypeSymbol;
}
return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations.FirstOrNone();
}
private static bool ReportAnyMismatchedConstraints(MethodSymbol interfaceMethod, TypeSymbol implementingType, MethodSymbol implicitImpl, BindingDiagnosticBag diagnostics)
{
Debug.Assert(interfaceMethod.Arity == implicitImpl.Arity);
bool result = false;
var arity = interfaceMethod.Arity;
if (arity > 0)
{
var typeParameters1 = interfaceMethod.TypeParameters;
var typeParameters2 = implicitImpl.TypeParameters;
var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity);
var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true);
var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true);
// Report any mismatched method constraints.
for (int i = 0; i < arity; i++)
{
var typeParameter1 = typeParameters1[i];
var typeParameter2 = typeParameters2[i];
if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2))
{
// If the matching method for the interface member is defined on the implementing type,
// the matching method location is used for the error. Otherwise, the location of the
// implementing type is used. (This differs from Dev10 which associates the error with
// the closest method always. That behavior can be confusing though, since in the case
// of "interface I { M; } class A { M; } class B : A, I { }", this means reporting an error on
// A.M that it does not satisfy I.M even though A does not implement I. Furthermore if
// A is defined in metadata, there is no location for A.M. Instead, we simply report the
// error on B if the match to I.M is in a base class.)
diagnostics.Add(ErrorCode.ERR_ImplBadConstraints, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl), typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod);
}
else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2))
{
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, GetImplicitImplementationDiagnosticLocation(interfaceMethod, implementingType, implicitImpl),
typeParameter2.Name, implicitImpl, typeParameter1.Name, interfaceMethod);
}
}
}
return result;
}
internal static Location GetImplicitImplementationDiagnosticLocation(Symbol interfaceMember, TypeSymbol implementingType, Symbol member)
{
if (TypeSymbol.Equals(member.ContainingType, implementingType, TypeCompareKind.ConsiderEverything2))
{
return member.Locations[0];
}
else
{
var @interface = interfaceMember.ContainingType;
SourceMemberContainerTypeSymbol snt = implementingType as SourceMemberContainerTypeSymbol;
return snt?.GetImplementsLocation(@interface) ?? implementingType.Locations[0];
}
}
/// <summary>
/// Search the declared members of a type for one that could be an implementation
/// of a given interface member (depending on interface declarations).
/// </summary>
/// <param name="interfaceMember">The interface member being implemented.</param>
/// <param name="implementingTypeIsFromSomeCompilation">True if the implementing type is from some compilation (i.e. not from metadata).</param>
/// <param name="currType">The type on which we are looking for a declared implementation of the interface member.</param>
/// <param name="implicitImpl">A member on currType that could implement the interface, or null.</param>
/// <param name="closeMismatch">A member on currType that could have been an attempt to implement the interface, or null.</param>
/// <remarks>
/// There is some similarity between this member and OverriddenOrHiddenMembersHelpers.FindOverriddenOrHiddenMembersInType.
/// When making changes to this member, think about whether or not they should also be applied in MemberSymbol.
/// One key difference is that custom modifiers are considered when looking up overridden members, but
/// not when looking up implicit implementations. We're preserving this behavior from Dev10.
/// </remarks>
private static void FindPotentialImplicitImplementationMemberDeclaredInType(
Symbol interfaceMember,
bool implementingTypeIsFromSomeCompilation,
TypeSymbol currType,
out Symbol implicitImpl,
out Symbol closeMismatch)
{
implicitImpl = null;
closeMismatch = null;
bool? isOperator = null;
if (interfaceMember is MethodSymbol interfaceMethod)
{
isOperator = interfaceMethod.MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion;
}
foreach (Symbol member in currType.GetMembers(interfaceMember.Name))
{
if (member.Kind == interfaceMember.Kind)
{
if (isOperator.HasValue &&
(((MethodSymbol)member).MethodKind is MethodKind.UserDefinedOperator or MethodKind.Conversion) != isOperator.GetValueOrDefault())
{
continue;
}
if (IsInterfaceMemberImplementation(member, interfaceMember, implementingTypeIsFromSomeCompilation))
{
implicitImpl = member;
return;
}
// If we haven't found a match, do a weaker comparison that ignores static-ness, accessibility, and return type.
else if ((object)closeMismatch == null && implementingTypeIsFromSomeCompilation)
{
// We can ignore custom modifiers here, because our goal is to improve the helpfulness
// of an error we're already giving, rather than to generate a new error.
if (MemberSignatureComparer.CSharpCloseImplicitImplementationComparer.Equals(interfaceMember, member))
{
closeMismatch = member;
}
}
}
}
}
/// <summary>
/// To implement an interface member, a candidate member must be public, non-static, and have
/// the same signature. "Have the same signature" has a looser definition if the type implementing
/// the interface is from source.
/// </summary>
/// <remarks>
/// PROPERTIES:
/// NOTE: we're not checking whether this property has at least the accessors
/// declared in the interface. Dev10 considers it a match either way and,
/// reports failure to implement accessors separately.
///
/// If the implementing type (i.e. the type with the interface in its interface
/// list) is in source, then we can ignore custom modifiers in/on the property
/// type because they will be copied into the bridge property that explicitly
/// implements the interface property (or they would be, if we created such
/// a bridge property). Bridge *methods* (not properties) are inserted in
/// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation.
///
/// CONSIDER: The spec for interface mapping (13.4.4) could be interpreted to mean that this
/// property is not an implementation unless it has an accessor for each accessor of the
/// interface property. For now, we prefer to represent that case as having an implemented
/// property and an unimplemented accessor because it makes finding accessor implementations
/// much easier. If we decide that we want the API to report the property as unimplemented,
/// then it might be appropriate to keep current result internally and just check the accessors
/// before returning the value from the public API (similar to the way MethodSymbol.OverriddenMethod
/// filters MethodSymbol.OverriddenOrHiddenMembers.
/// </remarks>
private static bool IsInterfaceMemberImplementation(Symbol candidateMember, Symbol interfaceMember, bool implementingTypeIsFromSomeCompilation)
{
if (candidateMember.DeclaredAccessibility != Accessibility.Public || candidateMember.IsStatic != interfaceMember.IsStatic)
{
return false;
}
else if (HaveInitOnlyMismatch(candidateMember, interfaceMember))
{
return false;
}
else if (implementingTypeIsFromSomeCompilation)
{
// We're specifically ignoring custom modifiers for source types because that's what Dev10 does.
// Inexact matches are acceptable because we'll just generate bridge members - explicit implementations
// with exact signatures that delegate to the inexact match. This happens automatically in
// SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation.
return MemberSignatureComparer.CSharpImplicitImplementationComparer.Equals(interfaceMember, candidateMember);
}
else
{
// NOTE: Dev10 seems to use the C# rules in this case as well, but it doesn't give diagnostics about
// the failure of a metadata type to implement an interface so there's no problem with reporting the
// CLI interpretation instead. For example, using this comparer might allow a member with a ref
// parameter to implement a member with an out parameter - which Dev10 would not allow - but that's
// okay because Dev10's behavior is not observable.
return MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(interfaceMember, candidateMember);
}
}
protected MultiDictionary<Symbol, Symbol>.ValueSet GetExplicitImplementationForInterfaceMember(Symbol interfaceMember)
{
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
return default;
}
if (info.explicitInterfaceImplementationMap == null)
{
Interlocked.CompareExchange(ref info.explicitInterfaceImplementationMap, MakeExplicitInterfaceImplementationMap(), null);
}
return info.explicitInterfaceImplementationMap[interfaceMember];
}
private MultiDictionary<Symbol, Symbol> MakeExplicitInterfaceImplementationMap()
{
var map = new MultiDictionary<Symbol, Symbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance);
foreach (var member in this.GetMembersUnordered())
{
foreach (var interfaceMember in member.GetExplicitInterfaceImplementations())
{
Debug.Assert(interfaceMember.Kind != SymbolKind.Method || (object)interfaceMember == ((MethodSymbol)interfaceMember).ConstructedFrom);
map.Add(interfaceMember, member);
}
}
return map;
}
#nullable enable
/// <summary>
/// If implementation of an interface method <paramref name="interfaceMethod"/> will be accompanied with
/// a MethodImpl entry in metadata, information about which isn't already exposed through
/// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API, this method returns the "Body" part
/// of the MethodImpl entry, i.e. the method that implements the <paramref name="interfaceMethod"/>.
/// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases,
/// the result is the method that the language considers to implement the <paramref name="interfaceMethod"/>,
/// rather than the forwarding method. In other words, it is the method that the forwarding method forwards to.
/// </summary>
/// <param name="interfaceMethod">The interface method that is going to be implemented by using synthesized MethodImpl entry.</param>
/// <returns></returns>
protected MethodSymbol? GetBodyOfSynthesizedInterfaceMethodImpl(MethodSymbol interfaceMethod)
{
var info = this.GetInterfaceInfo();
if (info == s_noInterfaces)
{
return null;
}
if (info.synthesizedMethodImplMap == null)
{
Interlocked.CompareExchange(ref info.synthesizedMethodImplMap, makeSynthesizedMethodImplMap(), null);
}
if (info.synthesizedMethodImplMap.TryGetValue(interfaceMethod, out MethodSymbol? result))
{
return result;
}
return null;
ImmutableDictionary<MethodSymbol, MethodSymbol> makeSynthesizedMethodImplMap()
{
var map = ImmutableDictionary.CreateBuilder<MethodSymbol, MethodSymbol>(ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance);
foreach ((MethodSymbol body, MethodSymbol implemented) in this.SynthesizedInterfaceMethodImpls())
{
map.Add(implemented, body);
}
return map.ToImmutable();
}
}
/// <summary>
/// Returns information about interface method implementations that will be accompanied with
/// MethodImpl entries in metadata, information about which isn't already exposed through
/// <see cref="MethodSymbol.ExplicitInterfaceImplementations"/> API. The "Body" is the method that
/// implements the interface method "Implemented".
/// Some of the MethodImpl entries could require synthetic forwarding methods. In such cases,
/// the "Body" is the method that the language considers to implement the interface method,
/// the "Implemented", rather than the forwarding method. In other words, it is the method that
/// the forwarding method forwards to.
/// </summary>
internal abstract IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls();
#nullable disable
protected class ExplicitInterfaceImplementationTargetMemberEqualityComparer : IEqualityComparer<Symbol>
{
public static readonly ExplicitInterfaceImplementationTargetMemberEqualityComparer Instance = new ExplicitInterfaceImplementationTargetMemberEqualityComparer();
private ExplicitInterfaceImplementationTargetMemberEqualityComparer() { }
public bool Equals(Symbol x, Symbol y)
{
return x.OriginalDefinition == y.OriginalDefinition &&
x.ContainingType.Equals(y.ContainingType, TypeCompareKind.CLRSignatureCompareOptions);
}
public int GetHashCode(Symbol obj)
{
return obj.OriginalDefinition.GetHashCode();
}
}
#endregion Interface member checks
#region Abstract base type checks
/// <summary>
/// The set of abstract members in declared in this type or declared in a base type and not overridden.
/// </summary>
internal ImmutableHashSet<Symbol> AbstractMembers
{
get
{
if (_lazyAbstractMembers == null)
{
Interlocked.CompareExchange(ref _lazyAbstractMembers, ComputeAbstractMembers(), null);
}
return _lazyAbstractMembers;
}
}
private ImmutableHashSet<Symbol> ComputeAbstractMembers()
{
var abstractMembers = ImmutableHashSet.Create<Symbol>();
var overriddenMembers = ImmutableHashSet.Create<Symbol>();
foreach (var member in this.GetMembersUnordered())
{
if (this.IsAbstract && member.IsAbstract && member.Kind != SymbolKind.NamedType)
{
abstractMembers = abstractMembers.Add(member);
}
Symbol overriddenMember = null;
switch (member.Kind)
{
case SymbolKind.Method:
{
overriddenMember = ((MethodSymbol)member).OverriddenMethod;
break;
}
case SymbolKind.Property:
{
overriddenMember = ((PropertySymbol)member).OverriddenProperty;
break;
}
case SymbolKind.Event:
{
overriddenMember = ((EventSymbol)member).OverriddenEvent;
break;
}
}
if ((object)overriddenMember != null)
{
overriddenMembers = overriddenMembers.Add(overriddenMember);
}
}
if ((object)this.BaseTypeNoUseSiteDiagnostics != null && this.BaseTypeNoUseSiteDiagnostics.IsAbstract)
{
foreach (var baseAbstractMember in this.BaseTypeNoUseSiteDiagnostics.AbstractMembers)
{
if (!overriddenMembers.Contains(baseAbstractMember))
{
abstractMembers = abstractMembers.Add(baseAbstractMember);
}
}
}
return abstractMembers;
}
#endregion Abstract base type checks
[Obsolete("Use TypeWithAnnotations.Is method.", true)]
internal bool Equals(TypeWithAnnotations other)
{
throw ExceptionUtilities.Unreachable;
}
public static bool Equals(TypeSymbol left, TypeSymbol right, TypeCompareKind comparison)
{
if (left is null)
{
return right is null;
}
return left.Equals(right, comparison);
}
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator ==(TypeSymbol left, TypeSymbol right)
=> throw ExceptionUtilities.Unreachable;
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator !=(TypeSymbol left, TypeSymbol right)
=> throw ExceptionUtilities.Unreachable;
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator ==(Symbol left, TypeSymbol right)
=> throw ExceptionUtilities.Unreachable;
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator !=(Symbol left, TypeSymbol right)
=> throw ExceptionUtilities.Unreachable;
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator ==(TypeSymbol left, Symbol right)
=> throw ExceptionUtilities.Unreachable;
[Obsolete("Use 'TypeSymbol.Equals(TypeSymbol, TypeSymbol, TypeCompareKind)' method.", true)]
public static bool operator !=(TypeSymbol left, Symbol right)
=> throw ExceptionUtilities.Unreachable;
internal ITypeSymbol GetITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
if (nullableAnnotation == DefaultNullableAnnotation)
{
return (ITypeSymbol)this.ISymbol;
}
return CreateITypeSymbol(nullableAnnotation);
}
internal CodeAnalysis.NullableAnnotation DefaultNullableAnnotation => NullableAnnotationExtensions.ToPublicAnnotation(this, NullableAnnotation.Oblivious);
protected abstract ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation);
TypeKind ITypeSymbolInternal.TypeKind => this.TypeKind;
SpecialType ITypeSymbolInternal.SpecialType => this.SpecialType;
bool ITypeSymbolInternal.IsReferenceType => this.IsReferenceType;
bool ITypeSymbolInternal.IsValueType => this.IsValueType;
ITypeSymbol ITypeSymbolInternal.GetITypeSymbol()
{
return GetITypeSymbol(DefaultNullableAnnotation);
}
internal abstract bool IsRecord { get; }
internal abstract bool IsRecordStruct { get; }
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/Core/Def/ValueTracking/BindableTextBlock.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.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.ValueTracking
{
internal class BindableTextBlock : TextBlock
{
public IList<Inline> InlineCollection
{
get { return (ObservableCollection<Inline>)GetValue(InlineListProperty); }
set { SetValue(InlineListProperty, value); }
}
public static readonly DependencyProperty InlineListProperty =
DependencyProperty.Register(nameof(InlineCollection), typeof(IList<Inline>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged));
private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var textBlock = (BindableTextBlock)sender;
var newList = (IList<Inline>)e.NewValue;
textBlock.Inlines.Clear();
foreach (var inline in newList)
{
textBlock.Inlines.Add(inline);
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.ValueTracking
{
internal class BindableTextBlock : TextBlock
{
public IList<Inline> InlineCollection
{
get { return (ObservableCollection<Inline>)GetValue(InlineListProperty); }
set { SetValue(InlineListProperty, value); }
}
public static readonly DependencyProperty InlineListProperty =
DependencyProperty.Register(nameof(InlineCollection), typeof(IList<Inline>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged));
private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var textBlock = (BindableTextBlock)sender;
var newList = (IList<Inline>)e.NewValue;
textBlock.Inlines.Clear();
foreach (var inline in newList)
{
textBlock.Inlines.Add(inline);
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Core/Portable/Shared/Utilities/DocumentationComment.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.Linq;
using System.Xml;
using XmlNames = Roslyn.Utilities.DocumentationCommentXmlNames;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
/// <summary>
/// A documentation comment derived from either source text or metadata.
/// </summary>
internal sealed class DocumentationComment
{
/// <summary>
/// True if an error occurred when parsing.
/// </summary>
public bool HadXmlParseError { get; private set; }
/// <summary>
/// The full XML text of this tag.
/// </summary>
public string FullXmlFragment { get; private set; }
/// <summary>
/// The text in the <example> tag. Null if no tag existed.
/// </summary>
public string? ExampleText { get; private set; }
/// <summary>
/// The text in the <summary> tag. Null if no tag existed.
/// </summary>
public string? SummaryText { get; private set; }
/// <summary>
/// The text in the <returns> tag. Null if no tag existed.
/// </summary>
public string? ReturnsText { get; private set; }
/// <summary>
/// The text in the <value> tag. Null if no tag existed.
/// </summary>
public string? ValueText { get; private set; }
/// <summary>
/// The text in the <remarks> tag. Null if no tag existed.
/// </summary>
public string? RemarksText { get; private set; }
/// <summary>
/// The names of items in <param> tags.
/// </summary>
public ImmutableArray<string> ParameterNames { get; private set; }
/// <summary>
/// The names of items in <typeparam> tags.
/// </summary>
public ImmutableArray<string> TypeParameterNames { get; private set; }
/// <summary>
/// The types of items in <exception> tags.
/// </summary>
public ImmutableArray<string> ExceptionTypes { get; private set; }
/// <summary>
/// The item named in the <completionlist> tag's cref attribute.
/// Null if the tag or cref attribute didn't exist.
/// </summary>
public string? CompletionListCref { get; private set; }
/// <summary>
/// Used for <see cref="CommentBuilder.TrimEachLine"/> method, to prevent new allocation of string
/// </summary>
private static readonly string[] s_NewLineAsStringArray = new string[] { "\n" };
private DocumentationComment(string fullXmlFragment)
{
FullXmlFragment = fullXmlFragment;
ParameterNames = ImmutableArray<string>.Empty;
TypeParameterNames = ImmutableArray<string>.Empty;
ExceptionTypes = ImmutableArray<string>.Empty;
}
/// <summary>
/// Cache of the most recently parsed fragment and the resulting DocumentationComment
/// </summary>
private static volatile DocumentationComment? s_cacheLastXmlFragmentParse;
/// <summary>
/// Parses and constructs a <see cref="DocumentationComment" /> from the given fragment of XML.
/// </summary>
/// <param name="xml">The fragment of XML to parse.</param>
/// <returns>A DocumentationComment instance.</returns>
public static DocumentationComment FromXmlFragment(string xml)
{
var result = s_cacheLastXmlFragmentParse;
if (result == null || result.FullXmlFragment != xml)
{
// Cache miss
result = CommentBuilder.Parse(xml);
s_cacheLastXmlFragmentParse = result;
}
return result;
}
/// <summary>
/// Helper class for parsing XML doc comments. Encapsulates the state required during parsing.
/// </summary>
private class CommentBuilder
{
private readonly DocumentationComment _comment;
private ImmutableArray<string>.Builder? _parameterNamesBuilder;
private ImmutableArray<string>.Builder? _typeParameterNamesBuilder;
private ImmutableArray<string>.Builder? _exceptionTypesBuilder;
private Dictionary<string, ImmutableArray<string>.Builder>? _exceptionTextBuilders;
/// <summary>
/// Parse and construct a <see cref="DocumentationComment" /> from the given fragment of XML.
/// </summary>
/// <param name="xml">The fragment of XML to parse.</param>
/// <returns>A DocumentationComment instance.</returns>
public static DocumentationComment Parse(string xml)
{
try
{
return new CommentBuilder(xml).ParseInternal(xml);
}
catch (Exception)
{
// It would be nice if we only had to catch XmlException to handle invalid XML
// while parsing doc comments. Unfortunately, other exceptions can also occur,
// so we just catch them all. See Dev12 Bug 612456 for an example.
return new DocumentationComment(xml) { HadXmlParseError = true };
}
}
private CommentBuilder(string xml)
=> _comment = new DocumentationComment(xml);
private DocumentationComment ParseInternal(string xml)
{
XmlFragmentParser.ParseFragment(xml, ParseCallback, this);
if (_exceptionTextBuilders != null)
{
foreach (var typeAndBuilderPair in _exceptionTextBuilders)
{
_comment._exceptionTexts.Add(typeAndBuilderPair.Key, typeAndBuilderPair.Value.AsImmutable());
}
}
_comment.ParameterNames = _parameterNamesBuilder == null ? ImmutableArray<string>.Empty : _parameterNamesBuilder.ToImmutable();
_comment.TypeParameterNames = _typeParameterNamesBuilder == null ? ImmutableArray<string>.Empty : _typeParameterNamesBuilder.ToImmutable();
_comment.ExceptionTypes = _exceptionTypesBuilder == null ? ImmutableArray<string>.Empty : _exceptionTypesBuilder.ToImmutable();
return _comment;
}
private static void ParseCallback(XmlReader reader, CommentBuilder builder)
=> builder.ParseCallback(reader);
private static string TrimEachLine(string text)
=> string.Join(Environment.NewLine, text.Split(s_NewLineAsStringArray, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()));
private void ParseCallback(XmlReader reader)
{
if (reader.NodeType == XmlNodeType.Element)
{
var localName = reader.LocalName;
if (XmlNames.ElementEquals(localName, XmlNames.ExampleElementName) && _comment.ExampleText == null)
{
_comment.ExampleText = TrimEachLine(reader.ReadInnerXml());
}
else if (XmlNames.ElementEquals(localName, XmlNames.SummaryElementName) && _comment.SummaryText == null)
{
_comment.SummaryText = TrimEachLine(reader.ReadInnerXml());
}
else if (XmlNames.ElementEquals(localName, XmlNames.ReturnsElementName) && _comment.ReturnsText == null)
{
_comment.ReturnsText = TrimEachLine(reader.ReadInnerXml());
}
else if (XmlNames.ElementEquals(localName, XmlNames.ValueElementName) && _comment.ValueText == null)
{
_comment.ValueText = TrimEachLine(reader.ReadInnerXml());
}
else if (XmlNames.ElementEquals(localName, XmlNames.RemarksElementName) && _comment.RemarksText == null)
{
_comment.RemarksText = TrimEachLine(reader.ReadInnerXml());
}
else if (XmlNames.ElementEquals(localName, XmlNames.ParameterElementName))
{
var name = reader.GetAttribute(XmlNames.NameAttributeName);
var paramText = reader.ReadInnerXml();
if (!string.IsNullOrWhiteSpace(name) && !_comment._parameterTexts.ContainsKey(name))
{
(_parameterNamesBuilder ?? (_parameterNamesBuilder = ImmutableArray.CreateBuilder<string>())).Add(name);
_comment._parameterTexts.Add(name, TrimEachLine(paramText));
}
}
else if (XmlNames.ElementEquals(localName, XmlNames.TypeParameterElementName))
{
var name = reader.GetAttribute(XmlNames.NameAttributeName);
var typeParamText = reader.ReadInnerXml();
if (!string.IsNullOrWhiteSpace(name) && !_comment._typeParameterTexts.ContainsKey(name))
{
(_typeParameterNamesBuilder ?? (_typeParameterNamesBuilder = ImmutableArray.CreateBuilder<string>())).Add(name);
_comment._typeParameterTexts.Add(name, TrimEachLine(typeParamText));
}
}
else if (XmlNames.ElementEquals(localName, XmlNames.ExceptionElementName))
{
var type = reader.GetAttribute(XmlNames.CrefAttributeName);
var exceptionText = reader.ReadInnerXml();
if (!string.IsNullOrWhiteSpace(type))
{
if (_exceptionTextBuilders == null || !_exceptionTextBuilders.ContainsKey(type))
{
(_exceptionTypesBuilder ?? (_exceptionTypesBuilder = ImmutableArray.CreateBuilder<string>())).Add(type);
(_exceptionTextBuilders ?? (_exceptionTextBuilders = new Dictionary<string, ImmutableArray<string>.Builder>())).Add(type, ImmutableArray.CreateBuilder<string>());
}
_exceptionTextBuilders[type].Add(exceptionText);
}
}
else if (XmlNames.ElementEquals(localName, XmlNames.CompletionListElementName))
{
var cref = reader.GetAttribute(XmlNames.CrefAttributeName);
if (!string.IsNullOrWhiteSpace(cref))
{
_comment.CompletionListCref = cref;
}
reader.ReadInnerXml();
}
else
{
// This is an element we don't handle. Skip it.
reader.Read();
}
}
else
{
// We came across something that isn't a start element, like a block of text.
// Skip it.
reader.Read();
}
}
}
private readonly Dictionary<string, string> _parameterTexts = new();
private readonly Dictionary<string, string> _typeParameterTexts = new();
private readonly Dictionary<string, ImmutableArray<string>> _exceptionTexts = new();
/// <summary>
/// Returns the text for a given parameter, or null if no documentation was given for the parameter.
/// </summary>
public string? GetParameterText(string parameterName)
{
_parameterTexts.TryGetValue(parameterName, out var text);
return text;
}
/// <summary>
/// Returns the text for a given type parameter, or null if no documentation was given for the type parameter.
/// </summary>
public string? GetTypeParameterText(string typeParameterName)
{
_typeParameterTexts.TryGetValue(typeParameterName, out var text);
return text;
}
/// <summary>
/// Returns the texts for a given exception, or an empty <see cref="ImmutableArray"/> if no documentation was given for the exception.
/// </summary>
public ImmutableArray<string> GetExceptionTexts(string exceptionName)
{
_exceptionTexts.TryGetValue(exceptionName, out var texts);
if (texts.IsDefault)
{
// If the exception wasn't found, TryGetValue will set "texts" to a default value.
// To be friendly, we want to return an empty array rather than a null array.
texts = ImmutableArray.Create<string>();
}
return texts;
}
/// <summary>
/// An empty comment.
/// </summary>
public static readonly DocumentationComment Empty = new(string.Empty);
}
}
| // Licensed to the .NET Foundation under one or more 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.Linq;
using System.Xml;
using XmlNames = Roslyn.Utilities.DocumentationCommentXmlNames;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
/// <summary>
/// A documentation comment derived from either source text or metadata.
/// </summary>
internal sealed class DocumentationComment
{
/// <summary>
/// True if an error occurred when parsing.
/// </summary>
public bool HadXmlParseError { get; private set; }
/// <summary>
/// The full XML text of this tag.
/// </summary>
public string FullXmlFragment { get; private set; }
/// <summary>
/// The text in the <example> tag. Null if no tag existed.
/// </summary>
public string? ExampleText { get; private set; }
/// <summary>
/// The text in the <summary> tag. Null if no tag existed.
/// </summary>
public string? SummaryText { get; private set; }
/// <summary>
/// The text in the <returns> tag. Null if no tag existed.
/// </summary>
public string? ReturnsText { get; private set; }
/// <summary>
/// The text in the <value> tag. Null if no tag existed.
/// </summary>
public string? ValueText { get; private set; }
/// <summary>
/// The text in the <remarks> tag. Null if no tag existed.
/// </summary>
public string? RemarksText { get; private set; }
/// <summary>
/// The names of items in <param> tags.
/// </summary>
public ImmutableArray<string> ParameterNames { get; private set; }
/// <summary>
/// The names of items in <typeparam> tags.
/// </summary>
public ImmutableArray<string> TypeParameterNames { get; private set; }
/// <summary>
/// The types of items in <exception> tags.
/// </summary>
public ImmutableArray<string> ExceptionTypes { get; private set; }
/// <summary>
/// The item named in the <completionlist> tag's cref attribute.
/// Null if the tag or cref attribute didn't exist.
/// </summary>
public string? CompletionListCref { get; private set; }
/// <summary>
/// Used for <see cref="CommentBuilder.TrimEachLine"/> method, to prevent new allocation of string
/// </summary>
private static readonly string[] s_NewLineAsStringArray = new string[] { "\n" };
private DocumentationComment(string fullXmlFragment)
{
FullXmlFragment = fullXmlFragment;
ParameterNames = ImmutableArray<string>.Empty;
TypeParameterNames = ImmutableArray<string>.Empty;
ExceptionTypes = ImmutableArray<string>.Empty;
}
/// <summary>
/// Cache of the most recently parsed fragment and the resulting DocumentationComment
/// </summary>
private static volatile DocumentationComment? s_cacheLastXmlFragmentParse;
/// <summary>
/// Parses and constructs a <see cref="DocumentationComment" /> from the given fragment of XML.
/// </summary>
/// <param name="xml">The fragment of XML to parse.</param>
/// <returns>A DocumentationComment instance.</returns>
public static DocumentationComment FromXmlFragment(string xml)
{
var result = s_cacheLastXmlFragmentParse;
if (result == null || result.FullXmlFragment != xml)
{
// Cache miss
result = CommentBuilder.Parse(xml);
s_cacheLastXmlFragmentParse = result;
}
return result;
}
/// <summary>
/// Helper class for parsing XML doc comments. Encapsulates the state required during parsing.
/// </summary>
private class CommentBuilder
{
private readonly DocumentationComment _comment;
private ImmutableArray<string>.Builder? _parameterNamesBuilder;
private ImmutableArray<string>.Builder? _typeParameterNamesBuilder;
private ImmutableArray<string>.Builder? _exceptionTypesBuilder;
private Dictionary<string, ImmutableArray<string>.Builder>? _exceptionTextBuilders;
/// <summary>
/// Parse and construct a <see cref="DocumentationComment" /> from the given fragment of XML.
/// </summary>
/// <param name="xml">The fragment of XML to parse.</param>
/// <returns>A DocumentationComment instance.</returns>
public static DocumentationComment Parse(string xml)
{
try
{
return new CommentBuilder(xml).ParseInternal(xml);
}
catch (Exception)
{
// It would be nice if we only had to catch XmlException to handle invalid XML
// while parsing doc comments. Unfortunately, other exceptions can also occur,
// so we just catch them all. See Dev12 Bug 612456 for an example.
return new DocumentationComment(xml) { HadXmlParseError = true };
}
}
private CommentBuilder(string xml)
=> _comment = new DocumentationComment(xml);
private DocumentationComment ParseInternal(string xml)
{
XmlFragmentParser.ParseFragment(xml, ParseCallback, this);
if (_exceptionTextBuilders != null)
{
foreach (var typeAndBuilderPair in _exceptionTextBuilders)
{
_comment._exceptionTexts.Add(typeAndBuilderPair.Key, typeAndBuilderPair.Value.AsImmutable());
}
}
_comment.ParameterNames = _parameterNamesBuilder == null ? ImmutableArray<string>.Empty : _parameterNamesBuilder.ToImmutable();
_comment.TypeParameterNames = _typeParameterNamesBuilder == null ? ImmutableArray<string>.Empty : _typeParameterNamesBuilder.ToImmutable();
_comment.ExceptionTypes = _exceptionTypesBuilder == null ? ImmutableArray<string>.Empty : _exceptionTypesBuilder.ToImmutable();
return _comment;
}
private static void ParseCallback(XmlReader reader, CommentBuilder builder)
=> builder.ParseCallback(reader);
private static string TrimEachLine(string text)
=> string.Join(Environment.NewLine, text.Split(s_NewLineAsStringArray, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()));
private void ParseCallback(XmlReader reader)
{
if (reader.NodeType == XmlNodeType.Element)
{
var localName = reader.LocalName;
if (XmlNames.ElementEquals(localName, XmlNames.ExampleElementName) && _comment.ExampleText == null)
{
_comment.ExampleText = TrimEachLine(reader.ReadInnerXml());
}
else if (XmlNames.ElementEquals(localName, XmlNames.SummaryElementName) && _comment.SummaryText == null)
{
_comment.SummaryText = TrimEachLine(reader.ReadInnerXml());
}
else if (XmlNames.ElementEquals(localName, XmlNames.ReturnsElementName) && _comment.ReturnsText == null)
{
_comment.ReturnsText = TrimEachLine(reader.ReadInnerXml());
}
else if (XmlNames.ElementEquals(localName, XmlNames.ValueElementName) && _comment.ValueText == null)
{
_comment.ValueText = TrimEachLine(reader.ReadInnerXml());
}
else if (XmlNames.ElementEquals(localName, XmlNames.RemarksElementName) && _comment.RemarksText == null)
{
_comment.RemarksText = TrimEachLine(reader.ReadInnerXml());
}
else if (XmlNames.ElementEquals(localName, XmlNames.ParameterElementName))
{
var name = reader.GetAttribute(XmlNames.NameAttributeName);
var paramText = reader.ReadInnerXml();
if (!string.IsNullOrWhiteSpace(name) && !_comment._parameterTexts.ContainsKey(name))
{
(_parameterNamesBuilder ?? (_parameterNamesBuilder = ImmutableArray.CreateBuilder<string>())).Add(name);
_comment._parameterTexts.Add(name, TrimEachLine(paramText));
}
}
else if (XmlNames.ElementEquals(localName, XmlNames.TypeParameterElementName))
{
var name = reader.GetAttribute(XmlNames.NameAttributeName);
var typeParamText = reader.ReadInnerXml();
if (!string.IsNullOrWhiteSpace(name) && !_comment._typeParameterTexts.ContainsKey(name))
{
(_typeParameterNamesBuilder ?? (_typeParameterNamesBuilder = ImmutableArray.CreateBuilder<string>())).Add(name);
_comment._typeParameterTexts.Add(name, TrimEachLine(typeParamText));
}
}
else if (XmlNames.ElementEquals(localName, XmlNames.ExceptionElementName))
{
var type = reader.GetAttribute(XmlNames.CrefAttributeName);
var exceptionText = reader.ReadInnerXml();
if (!string.IsNullOrWhiteSpace(type))
{
if (_exceptionTextBuilders == null || !_exceptionTextBuilders.ContainsKey(type))
{
(_exceptionTypesBuilder ?? (_exceptionTypesBuilder = ImmutableArray.CreateBuilder<string>())).Add(type);
(_exceptionTextBuilders ?? (_exceptionTextBuilders = new Dictionary<string, ImmutableArray<string>.Builder>())).Add(type, ImmutableArray.CreateBuilder<string>());
}
_exceptionTextBuilders[type].Add(exceptionText);
}
}
else if (XmlNames.ElementEquals(localName, XmlNames.CompletionListElementName))
{
var cref = reader.GetAttribute(XmlNames.CrefAttributeName);
if (!string.IsNullOrWhiteSpace(cref))
{
_comment.CompletionListCref = cref;
}
reader.ReadInnerXml();
}
else
{
// This is an element we don't handle. Skip it.
reader.Read();
}
}
else
{
// We came across something that isn't a start element, like a block of text.
// Skip it.
reader.Read();
}
}
}
private readonly Dictionary<string, string> _parameterTexts = new();
private readonly Dictionary<string, string> _typeParameterTexts = new();
private readonly Dictionary<string, ImmutableArray<string>> _exceptionTexts = new();
/// <summary>
/// Returns the text for a given parameter, or null if no documentation was given for the parameter.
/// </summary>
public string? GetParameterText(string parameterName)
{
_parameterTexts.TryGetValue(parameterName, out var text);
return text;
}
/// <summary>
/// Returns the text for a given type parameter, or null if no documentation was given for the type parameter.
/// </summary>
public string? GetTypeParameterText(string typeParameterName)
{
_typeParameterTexts.TryGetValue(typeParameterName, out var text);
return text;
}
/// <summary>
/// Returns the texts for a given exception, or an empty <see cref="ImmutableArray"/> if no documentation was given for the exception.
/// </summary>
public ImmutableArray<string> GetExceptionTexts(string exceptionName)
{
_exceptionTexts.TryGetValue(exceptionName, out var texts);
if (texts.IsDefault)
{
// If the exception wasn't found, TryGetValue will set "texts" to a default value.
// To be friendly, we want to return an empty array rather than a null array.
texts = ImmutableArray.Create<string>();
}
return texts;
}
/// <summary>
/// An empty comment.
/// </summary>
public static readonly DocumentationComment Empty = new(string.Empty);
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/CSharpTest/Structure/DocumentationCommentStructureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class DocumentationCommentStructureTests : AbstractCSharpSyntaxNodeStructureTests<DocumentationCommentTriviaSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new DocumentationCommentStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationCommentWithoutSummaryTag1()
{
const string code = @"
{|span:/// $$XML doc comment
/// some description
/// of
/// the comment|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// XML doc comment ...", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationCommentWithoutSummaryTag2()
{
const string code = @"
{|span:/** $$Block comment
* some description
* of
* the comment
*/|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/** Block comment ...", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationCommentWithoutSummaryTag3()
{
const string code = @"
{|span:/// $$<param name=""tree""></param>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <param name=\"tree\"></param> ...", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationComment()
{
const string code = @"
{|span:/// <summary>
/// $$Hello C#!
/// </summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationCommentWithLongBannerText()
{
var code = @"
{|span:/// $$<summary>
/// " + new string('x', 240) + @"
/// </summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> " + new string('x', 106) + " ...", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestMultilineDocumentationComment()
{
const string code = @"
{|span:/** <summary>
$$Hello C#!
</summary> */|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/** <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIndentedDocumentationComment()
{
const string code = @"
{|span:/// <summary>
/// $$Hello C#!
/// </summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIndentedMultilineDocumentationComment()
{
const string code = @"
{|span:/** <summary>
$$Hello C#!
</summary> */|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/** <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationCommentOnASingleLine()
{
const string code = @"
{|span:/// <summary>$$Hello C#!</summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary>Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestMultilineDocumentationCommentOnASingleLine()
{
const string code = @"
{|span:/** <summary>$$Hello C#!</summary> */|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/** <summary>Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIndentedDocumentationCommentOnASingleLine()
{
const string code = @"
{|span:/// <summary>$$Hello C#!</summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary>Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIndentedMultilineDocumentationCommentOnASingleLine()
{
const string code = @"
{|span:/** <summary>$$Hello C#!</summary> */|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/** <summary>Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestMultilineSummaryInDocumentationComment1()
{
const string code = @"
{|span:/// <summary>
/// $$Hello
/// C#!
/// </summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestMultilineSummaryInDocumentationComment2()
{
const string code = @"
{|span:/// <summary>
/// $$Hello
///
/// C#!
/// </summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
[WorkItem(2129, "https://github.com/dotnet/roslyn/issues/2129")]
public async Task CrefInSummary()
{
const string code = @"
class C
{
{|span:/// $$<summary>
/// Summary with <see cref=""SeeClass"" />, <seealso cref=""SeeAlsoClass"" />,
/// <see langword=""null"" />, <typeparamref name=""T"" />, <paramref name=""t"" />, and <see unsupported-attribute=""not-supported"" />.
/// </summary>|}
public void M<T>(T t) { }
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Summary with SeeClass, SeeAlsoClass, null, T, t, and not-supported.", autoCollapse: true));
}
[WorkItem(402822, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestSummaryWithPunctuation()
{
const string code = @"
class C
{
{|span:/// $$<summary>
/// The main entrypoint for <see cref=""Program""/>.
/// </summary>
/// <param name=""args""></param>|}
void Main()
{
}
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> The main entrypoint for Program.", autoCollapse: true));
}
[WorkItem(20679, "https://github.com/dotnet/roslyn/issues/20679")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestSummaryWithAdditionalTags()
{
const string code = @"
public class Class1
{
{|span:/// $$<summary>
/// Initializes a <c>new</c> instance of the <see cref=""Class1"" /> class.
/// </summary>|}
public Class1()
{
}
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Initializes a new instance of the Class1 class.", autoCollapse: true));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure
{
public class DocumentationCommentStructureTests : AbstractCSharpSyntaxNodeStructureTests<DocumentationCommentTriviaSyntax>
{
internal override AbstractSyntaxStructureProvider CreateProvider() => new DocumentationCommentStructureProvider();
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationCommentWithoutSummaryTag1()
{
const string code = @"
{|span:/// $$XML doc comment
/// some description
/// of
/// the comment|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// XML doc comment ...", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationCommentWithoutSummaryTag2()
{
const string code = @"
{|span:/** $$Block comment
* some description
* of
* the comment
*/|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/** Block comment ...", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationCommentWithoutSummaryTag3()
{
const string code = @"
{|span:/// $$<param name=""tree""></param>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <param name=\"tree\"></param> ...", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationComment()
{
const string code = @"
{|span:/// <summary>
/// $$Hello C#!
/// </summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationCommentWithLongBannerText()
{
var code = @"
{|span:/// $$<summary>
/// " + new string('x', 240) + @"
/// </summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> " + new string('x', 106) + " ...", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestMultilineDocumentationComment()
{
const string code = @"
{|span:/** <summary>
$$Hello C#!
</summary> */|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/** <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIndentedDocumentationComment()
{
const string code = @"
{|span:/// <summary>
/// $$Hello C#!
/// </summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIndentedMultilineDocumentationComment()
{
const string code = @"
{|span:/** <summary>
$$Hello C#!
</summary> */|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/** <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestDocumentationCommentOnASingleLine()
{
const string code = @"
{|span:/// <summary>$$Hello C#!</summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary>Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestMultilineDocumentationCommentOnASingleLine()
{
const string code = @"
{|span:/** <summary>$$Hello C#!</summary> */|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/** <summary>Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIndentedDocumentationCommentOnASingleLine()
{
const string code = @"
{|span:/// <summary>$$Hello C#!</summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary>Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestIndentedMultilineDocumentationCommentOnASingleLine()
{
const string code = @"
{|span:/** <summary>$$Hello C#!</summary> */|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/** <summary>Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestMultilineSummaryInDocumentationComment1()
{
const string code = @"
{|span:/// <summary>
/// $$Hello
/// C#!
/// </summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestMultilineSummaryInDocumentationComment2()
{
const string code = @"
{|span:/// <summary>
/// $$Hello
///
/// C#!
/// </summary>|}
class Class3
{
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Hello C#!", autoCollapse: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
[WorkItem(2129, "https://github.com/dotnet/roslyn/issues/2129")]
public async Task CrefInSummary()
{
const string code = @"
class C
{
{|span:/// $$<summary>
/// Summary with <see cref=""SeeClass"" />, <seealso cref=""SeeAlsoClass"" />,
/// <see langword=""null"" />, <typeparamref name=""T"" />, <paramref name=""t"" />, and <see unsupported-attribute=""not-supported"" />.
/// </summary>|}
public void M<T>(T t) { }
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Summary with SeeClass, SeeAlsoClass, null, T, t, and not-supported.", autoCollapse: true));
}
[WorkItem(402822, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=402822")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestSummaryWithPunctuation()
{
const string code = @"
class C
{
{|span:/// $$<summary>
/// The main entrypoint for <see cref=""Program""/>.
/// </summary>
/// <param name=""args""></param>|}
void Main()
{
}
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> The main entrypoint for Program.", autoCollapse: true));
}
[WorkItem(20679, "https://github.com/dotnet/roslyn/issues/20679")]
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public async Task TestSummaryWithAdditionalTags()
{
const string code = @"
public class Class1
{
{|span:/// $$<summary>
/// Initializes a <c>new</c> instance of the <see cref=""Class1"" /> class.
/// </summary>|}
public Class1()
{
}
}";
await VerifyBlockSpansAsync(code,
Region("span", "/// <summary> Initializes a new instance of the Class1 class.", autoCollapse: true));
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/Portable/Operations/IOperation.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.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Root type for representing the abstract semantics of C# and VB statements and expressions.
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
[InternalImplementationOnly]
public interface IOperation
{
/// <summary>
/// IOperation that has this operation as a child. Null for the root.
/// </summary>
IOperation? Parent { get; }
/// <summary>
/// Identifies the kind of the operation.
/// </summary>
OperationKind Kind { get; }
/// <summary>
/// Syntax that was analyzed to produce the operation.
/// </summary>
SyntaxNode Syntax { get; }
/// <summary>
/// Result type of the operation, or null if the operation does not produce a result.
/// </summary>
ITypeSymbol? Type { get; }
/// <summary>
/// If the operation is an expression that evaluates to a constant value, <see cref="Optional{Object}.HasValue"/> is true and <see cref="Optional{Object}.Value"/> is the value of the expression. Otherwise, <see cref="Optional{Object}.HasValue"/> is false.
/// </summary>
Optional<object?> ConstantValue { get; }
/// <summary>
/// An array of child operations for this operation.
/// </summary>
IEnumerable<IOperation> Children { get; }
/// <summary>
/// The source language of the IOperation. Possible values are <see cref="LanguageNames.CSharp"/> and <see cref="LanguageNames.VisualBasic"/>.
/// </summary>
string Language { get; }
void Accept(OperationVisitor visitor);
TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument);
/// <summary>
/// Set to True if compiler generated /implicitly computed by compiler code
/// </summary>
bool IsImplicit { get; }
/// <summary>
/// Optional semantic model that was used to generate this operation.
/// Non-null for operations generated from source with <see cref="SemanticModel.GetOperation(SyntaxNode, System.Threading.CancellationToken)"/> API
/// and operation callbacks made to analyzers.
/// Null for operations inside a <see cref="FlowAnalysis.ControlFlowGraph"/>.
/// </summary>
SemanticModel? SemanticModel { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Root type for representing the abstract semantics of C# and VB statements and expressions.
/// </summary>
/// <remarks>
/// This interface is reserved for implementation by its associated APIs. We reserve the right to
/// change it in the future.
/// </remarks>
[InternalImplementationOnly]
public interface IOperation
{
/// <summary>
/// IOperation that has this operation as a child. Null for the root.
/// </summary>
IOperation? Parent { get; }
/// <summary>
/// Identifies the kind of the operation.
/// </summary>
OperationKind Kind { get; }
/// <summary>
/// Syntax that was analyzed to produce the operation.
/// </summary>
SyntaxNode Syntax { get; }
/// <summary>
/// Result type of the operation, or null if the operation does not produce a result.
/// </summary>
ITypeSymbol? Type { get; }
/// <summary>
/// If the operation is an expression that evaluates to a constant value, <see cref="Optional{Object}.HasValue"/> is true and <see cref="Optional{Object}.Value"/> is the value of the expression. Otherwise, <see cref="Optional{Object}.HasValue"/> is false.
/// </summary>
Optional<object?> ConstantValue { get; }
/// <summary>
/// An array of child operations for this operation.
/// </summary>
IEnumerable<IOperation> Children { get; }
/// <summary>
/// The source language of the IOperation. Possible values are <see cref="LanguageNames.CSharp"/> and <see cref="LanguageNames.VisualBasic"/>.
/// </summary>
string Language { get; }
void Accept(OperationVisitor visitor);
TResult? Accept<TArgument, TResult>(OperationVisitor<TArgument, TResult> visitor, TArgument argument);
/// <summary>
/// Set to True if compiler generated /implicitly computed by compiler code
/// </summary>
bool IsImplicit { get; }
/// <summary>
/// Optional semantic model that was used to generate this operation.
/// Non-null for operations generated from source with <see cref="SemanticModel.GetOperation(SyntaxNode, System.Threading.CancellationToken)"/> API
/// and operation callbacks made to analyzers.
/// Null for operations inside a <see cref="FlowAnalysis.ControlFlowGraph"/>.
/// </summary>
SemanticModel? SemanticModel { get; }
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/Core/Portable/UnusedReferences/ReferenceUpdate.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.UnusedReferences
{
internal sealed class ReferenceUpdate
{
/// <summary>
/// Indicates action to perform on the reference.
/// </summary>
public UpdateAction Action { get; set; }
/// <summary>
/// Gets the reference to be updated.
/// </summary>
public ReferenceInfo ReferenceInfo { get; }
public ReferenceUpdate(UpdateAction action, ReferenceInfo referenceInfo)
{
Action = action;
ReferenceInfo = referenceInfo;
}
}
}
| // Licensed to the .NET Foundation under one or more 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.UnusedReferences
{
internal sealed class ReferenceUpdate
{
/// <summary>
/// Indicates action to perform on the reference.
/// </summary>
public UpdateAction Action { get; set; }
/// <summary>
/// Gets the reference to be updated.
/// </summary>
public ReferenceInfo ReferenceInfo { get; }
public ReferenceUpdate(UpdateAction action, ReferenceInfo referenceInfo)
{
Action = action;
ReferenceInfo = referenceInfo;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/VisualBasic/Portable/Structure/Providers/EventDeclarationStructureProvider.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.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class EventDeclarationStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of EventStatementSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
eventDeclaration As EventStatementSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
CollectCommentsRegions(eventDeclaration, spans, optionProvider)
Dim block = TryCast(eventDeclaration.Parent, EventBlockSyntax)
If Not block?.EndEventStatement.IsMissing Then
spans.AddIfNotNull(CreateBlockSpanFromBlock(
block, bannerNode:=eventDeclaration, autoCollapse:=True,
type:=BlockTypes.Member, isCollapsible:=True))
CollectCommentsRegions(block.EndEventStatement, spans, optionProvider)
End If
End Sub
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.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class EventDeclarationStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of EventStatementSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
eventDeclaration As EventStatementSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
CollectCommentsRegions(eventDeclaration, spans, optionProvider)
Dim block = TryCast(eventDeclaration.Parent, EventBlockSyntax)
If Not block?.EndEventStatement.IsMissing Then
spans.AddIfNotNull(CreateBlockSpanFromBlock(
block, bannerNode:=eventDeclaration, autoCollapse:=True,
type:=BlockTypes.Member, isCollapsible:=True))
CollectCommentsRegions(block.EndEventStatement, spans, optionProvider)
End If
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/VisualBasic/Portable/Formatting/VisualBasicSyntaxFormattingService.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.Threading
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Shared.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Diagnostics
#If Not CODE_STYLE Then
Imports System.Composition
Imports Microsoft.CodeAnalysis.Host.Mef
#End If
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
#If Not CODE_STYLE Then
<ExportLanguageService(GetType(ISyntaxFormattingService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicSyntaxFormattingService
#Else
Friend Class VisualBasicSyntaxFormattingService
#End If
Inherits AbstractSyntaxFormattingService
Private ReadOnly _rules As ImmutableList(Of AbstractFormattingRule)
#If CODE_STYLE Then
Public Shared ReadOnly Instance As New VisualBasicSyntaxFormattingService
#End If
#If Not CODE_STYLE Then
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
#Else
Public Sub New()
#End If
_rules = ImmutableList.Create(Of AbstractFormattingRule)(
New StructuredTriviaFormattingRule(),
New ElasticTriviaFormattingRule(),
New AdjustSpaceFormattingRule(),
New AlignTokensFormattingRule(),
New NodeBasedFormattingRule(),
DefaultOperationProvider.Instance)
End Sub
Public Overrides Function GetDefaultFormattingRules() As IEnumerable(Of AbstractFormattingRule)
Return _rules
End Function
Protected Overrides Function CreateAggregatedFormattingResult(node As SyntaxNode, results As IList(Of AbstractFormattingResult), Optional formattingSpans As SimpleIntervalTree(Of TextSpan, TextSpanIntervalIntrospector) = Nothing) As IFormattingResult
Return New AggregatedFormattingResult(node, results, formattingSpans)
End Function
Protected Overrides Function Format(root As SyntaxNode, options As AnalyzerConfigOptions, formattingRules As IEnumerable(Of AbstractFormattingRule), token1 As SyntaxToken, token2 As SyntaxToken, cancellationToken As CancellationToken) As AbstractFormattingResult
Return New VisualBasicFormatEngine(root, options, formattingRules, token1, token2).Format(cancellationToken)
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.Threading
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Shared.Collections
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.Diagnostics
#If Not CODE_STYLE Then
Imports System.Composition
Imports Microsoft.CodeAnalysis.Host.Mef
#End If
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
#If Not CODE_STYLE Then
<ExportLanguageService(GetType(ISyntaxFormattingService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicSyntaxFormattingService
#Else
Friend Class VisualBasicSyntaxFormattingService
#End If
Inherits AbstractSyntaxFormattingService
Private ReadOnly _rules As ImmutableList(Of AbstractFormattingRule)
#If CODE_STYLE Then
Public Shared ReadOnly Instance As New VisualBasicSyntaxFormattingService
#End If
#If Not CODE_STYLE Then
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
#Else
Public Sub New()
#End If
_rules = ImmutableList.Create(Of AbstractFormattingRule)(
New StructuredTriviaFormattingRule(),
New ElasticTriviaFormattingRule(),
New AdjustSpaceFormattingRule(),
New AlignTokensFormattingRule(),
New NodeBasedFormattingRule(),
DefaultOperationProvider.Instance)
End Sub
Public Overrides Function GetDefaultFormattingRules() As IEnumerable(Of AbstractFormattingRule)
Return _rules
End Function
Protected Overrides Function CreateAggregatedFormattingResult(node As SyntaxNode, results As IList(Of AbstractFormattingResult), Optional formattingSpans As SimpleIntervalTree(Of TextSpan, TextSpanIntervalIntrospector) = Nothing) As IFormattingResult
Return New AggregatedFormattingResult(node, results, formattingSpans)
End Function
Protected Overrides Function Format(root As SyntaxNode, options As AnalyzerConfigOptions, formattingRules As IEnumerable(Of AbstractFormattingRule), token1 As SyntaxToken, token2 As SyntaxToken, cancellationToken As CancellationToken) As AbstractFormattingResult
Return New VisualBasicFormatEngine(root, options, formattingRules, token1, token2).Format(cancellationToken)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/VisualBasic/Portable/Formatting/VisualBasicNewDocumentFormattingService.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.Composition
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
<ExportLanguageService(GetType(INewDocumentFormattingService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicNewDocumentFormattingService
Inherits AbstractNewDocumentFormattingService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(<ImportMany> providers As IEnumerable(Of Lazy(Of INewDocumentFormattingProvider, LanguageMetadata)))
MyBase.New(providers)
End Sub
Protected Overrides ReadOnly Property Language As String = LanguageNames.VisualBasic
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.Composition
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
<ExportLanguageService(GetType(INewDocumentFormattingService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicNewDocumentFormattingService
Inherits AbstractNewDocumentFormattingService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(<ImportMany> providers As IEnumerable(Of Lazy(Of INewDocumentFormattingProvider, LanguageMetadata)))
MyBase.New(providers)
End Sub
Protected Overrides ReadOnly Property Language As String = LanguageNames.VisualBasic
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/MSBuildTaskTests/TestUtilities/EnumerableExtensions.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;
namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests
{
public static class EnumerableExtensions
{
public static IEnumerable<S> SelectWithIndex<T, S>(this IEnumerable<T> items, Func<T, int, S> selector)
{
int i = 0;
foreach (var item in items)
{
yield return selector(item, i++);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests
{
public static class EnumerableExtensions
{
public static IEnumerable<S> SelectWithIndex<T, S>(this IEnumerable<T> items, Func<T, int, S> selector)
{
int i = 0;
foreach (var item in items)
{
yield return selector(item, i++);
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/CSharp/Portable/GenerateConstructor/GenerateConstructorCodeFixProvider.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.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.GenerateMember;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructor
{
internal static class GenerateConstructorDiagnosticIds
{
public const string CS0122 = nameof(CS0122); // CS0122: 'C' is inaccessible due to its protection level
public const string CS1729 = nameof(CS1729); // CS1729: 'C' does not contain a constructor that takes n arguments
public const string CS1739 = nameof(CS1739); // CS1739: The best overload for 'Program' does not have a parameter named 'v'
public const string CS1503 = nameof(CS1503); // CS1503: Argument 1: cannot convert from 'T1' to 'T2'
public const string CS1660 = nameof(CS1660); // CS1660: Cannot convert lambda expression to type 'string[]' because it is not a delegate type
public const string CS7036 = nameof(CS7036); // CS7036: There is no argument given that corresponds to the required formal parameter 'v' of 'C.C(int)'
public static readonly ImmutableArray<string> AllDiagnosticIds =
ImmutableArray.Create(CS0122, CS1729, CS1739, CS1503, CS1660, CS7036);
public static readonly ImmutableArray<string> TooManyArgumentsDiagnosticIds =
ImmutableArray.Create(CS1729);
public static readonly ImmutableArray<string> CannotConvertDiagnosticIds =
ImmutableArray.Create(CS1503, CS1660);
}
/// <summary>
/// This <see cref="CodeFixProvider"/> gives users a way to generate constructors for an existing
/// type when a user tries to 'new' up an instance of that type with a set of parameter that does
/// not match any existing constructor. i.e. it is the equivalent of 'Generate-Method' but for
/// constructors. Parameters for the constructor will be picked in a manner similar to Generate-
/// Method. However, this type will also attempt to hook up those parameters to existing fields
/// and properties, or pass them to a this/base constructor if available.
///
/// Importantly, this type is not responsible for generating constructors for a type based on
/// the user selecting some fields/properties of that type. Nor is it responsible for generating
/// derived class constructors for all unmatched base class constructors in a type hierarchy.
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateConstructor), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.FullyQualify)]
internal class GenerateConstructorCodeFixProvider : AbstractGenerateMemberCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public GenerateConstructorCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => GenerateConstructorDiagnosticIds.AllDiagnosticIds;
protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync(
Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IGenerateConstructorService>();
return service.GenerateConstructorAsync(document, node, cancellationToken);
}
protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic)
{
return node is BaseObjectCreationExpressionSyntax ||
node is ConstructorInitializerSyntax ||
node is AttributeSyntax;
}
protected override SyntaxNode GetTargetNode(SyntaxNode node)
{
switch (node)
{
case ObjectCreationExpressionSyntax objectCreationNode:
return objectCreationNode.Type.GetRightmostName();
case AttributeSyntax attributeNode:
return attributeNode.Name;
}
return 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.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.GenerateMember;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructor
{
internal static class GenerateConstructorDiagnosticIds
{
public const string CS0122 = nameof(CS0122); // CS0122: 'C' is inaccessible due to its protection level
public const string CS1729 = nameof(CS1729); // CS1729: 'C' does not contain a constructor that takes n arguments
public const string CS1739 = nameof(CS1739); // CS1739: The best overload for 'Program' does not have a parameter named 'v'
public const string CS1503 = nameof(CS1503); // CS1503: Argument 1: cannot convert from 'T1' to 'T2'
public const string CS1660 = nameof(CS1660); // CS1660: Cannot convert lambda expression to type 'string[]' because it is not a delegate type
public const string CS7036 = nameof(CS7036); // CS7036: There is no argument given that corresponds to the required formal parameter 'v' of 'C.C(int)'
public static readonly ImmutableArray<string> AllDiagnosticIds =
ImmutableArray.Create(CS0122, CS1729, CS1739, CS1503, CS1660, CS7036);
public static readonly ImmutableArray<string> TooManyArgumentsDiagnosticIds =
ImmutableArray.Create(CS1729);
public static readonly ImmutableArray<string> CannotConvertDiagnosticIds =
ImmutableArray.Create(CS1503, CS1660);
}
/// <summary>
/// This <see cref="CodeFixProvider"/> gives users a way to generate constructors for an existing
/// type when a user tries to 'new' up an instance of that type with a set of parameter that does
/// not match any existing constructor. i.e. it is the equivalent of 'Generate-Method' but for
/// constructors. Parameters for the constructor will be picked in a manner similar to Generate-
/// Method. However, this type will also attempt to hook up those parameters to existing fields
/// and properties, or pass them to a this/base constructor if available.
///
/// Importantly, this type is not responsible for generating constructors for a type based on
/// the user selecting some fields/properties of that type. Nor is it responsible for generating
/// derived class constructors for all unmatched base class constructors in a type hierarchy.
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateConstructor), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.FullyQualify)]
internal class GenerateConstructorCodeFixProvider : AbstractGenerateMemberCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public GenerateConstructorCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => GenerateConstructorDiagnosticIds.AllDiagnosticIds;
protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync(
Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IGenerateConstructorService>();
return service.GenerateConstructorAsync(document, node, cancellationToken);
}
protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic)
{
return node is BaseObjectCreationExpressionSyntax ||
node is ConstructorInitializerSyntax ||
node is AttributeSyntax;
}
protected override SyntaxNode GetTargetNode(SyntaxNode node)
{
switch (node)
{
case ObjectCreationExpressionSyntax objectCreationNode:
return objectCreationNode.Type.GetRightmostName();
case AttributeSyntax attributeNode:
return attributeNode.Name;
}
return node;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefConstruction.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.Host.Mef
{
internal static class MefConstruction
{
internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider.";
internal const string FactoryMethodMessage = "This factory method only provides services for the MEF export 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
namespace Microsoft.CodeAnalysis.Host.Mef
{
internal static class MefConstruction
{
internal const string ImportingConstructorMessage = "This exported object must be obtained through the MEF export provider.";
internal const string FactoryMethodMessage = "This factory method only provides services for the MEF export provider.";
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/CSharpTest/Diagnostics/Configuration/ConfigureCodeStyle/BooleanCodeStyleOptionConfigurationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureCodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureCodeStyle
{
public abstract partial class BooleanCodeStyleOptionConfigurationTests : AbstractSuppressionDiagnosticTest
{
protected internal override string GetLanguage() => LanguageNames.CSharp;
protected override ParseOptions GetScriptOptions() => Options.Script;
internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>(
new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider());
}
public class TrueConfigurationTests : BooleanCodeStyleOptionConfigurationTests
{
protected override int CodeActionIndex => 0;
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_Empty_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1
dotnet_style_object_initializer = false:suggestion ; Comment2
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1
dotnet_style_object_initializer = true:suggestion ; Comment2
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidHeader_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = false:suggestion
[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_MaintainSeverity_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidRule_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
dotnet_style_object_initializerr = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
dotnet_style_object_initializerr = false
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
}
public class FalseConfigurationTests : BooleanCodeStyleOptionConfigurationTests
{
protected override int CodeActionIndex => 1;
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_Empty_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_False_NoSeveritySuffix()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = warning
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_ConflitingDotnetDiagnosticEntry()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = error
dotnet_style_object_initializer = true:warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = error
dotnet_style_object_initializer = false:warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidHeader_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = true:suggestion
[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_MaintainSeverity_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidRule_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureCodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureCodeStyle
{
public abstract partial class BooleanCodeStyleOptionConfigurationTests : AbstractSuppressionDiagnosticTest
{
protected internal override string GetLanguage() => LanguageNames.CSharp;
protected override ParseOptions GetScriptOptions() => Options.Script;
internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>(
new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureCodeStyleOptionCodeFixProvider());
}
public class TrueConfigurationTests : BooleanCodeStyleOptionConfigurationTests
{
protected override int CodeActionIndex => 0;
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_Empty_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1
dotnet_style_object_initializer = false:suggestion ; Comment2
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1
dotnet_style_object_initializer = true:suggestion ; Comment2
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidHeader_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = false:suggestion
[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/39466"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_MaintainSeverity_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidRule_True()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
dotnet_style_object_initializerr = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
dotnet_style_object_initializerr = false
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
}
public class FalseConfigurationTests : BooleanCodeStyleOptionConfigurationTests
{
protected override int CodeActionIndex => 1;
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_Empty_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_False_NoSeveritySuffix()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = true
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_DotnetDiagnosticEntry()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = warning
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_RuleExists_ConflitingDotnetDiagnosticEntry()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = error
dotnet_style_object_initializer = true:warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_diagnostic.IDE0017.severity = error
dotnet_style_object_initializer = false:warning
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidHeader_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb]
dotnet_style_object_initializer = true:suggestion
[*.{cs,vb}]
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_MaintainSeverity_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = true:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = new Customer();
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}]
dotnet_style_object_initializer = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
[ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public async Task ConfigureEditorconfig_InvalidRule_False()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
</AnalyzerConfigDocument>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath=""z:\\file.cs"">
class Program1
{
static void Main()
{
// dotnet_style_object_initializer = true
var obj = new Customer() { _age = 21 };
// dotnet_style_object_initializer = false
Customer obj2 = [|new Customer()|];
obj2._age = 21;
}
internal class Customer
{
public int _age;
public Customer()
{
}
}
}
</Document>
<AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs]
dotnet_style_object_initializerr = false:suggestion
# IDE0017: Simplify object initialization
dotnet_style_object_initializer = false
</AnalyzerConfigDocument>
</Project>
</Workspace>";
await TestInRegularAndScriptAsync(input, expected, CodeActionIndex);
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_GetHashCodeMethodSymbol.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.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Partial Friend NotInheritable Class AnonymousTypeManager
Partial Private NotInheritable Class AnonymousTypeGetHashCodeMethodSymbol
Inherits SynthesizedRegularMethodBase
Public Sub New(container As AnonymousTypeTemplateSymbol)
MyBase.New(VisualBasicSyntaxTree.Dummy.GetRoot(), container, WellKnownMemberNames.ObjectGetHashCode)
End Sub
Private ReadOnly Property AnonymousType As AnonymousTypeTemplateSymbol
Get
Return DirectCast(Me.m_containingType, AnonymousTypeTemplateSymbol)
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol
Get
Return Me.AnonymousType.Manager.System_Object__GetHashCode
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Public
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return AnonymousType.Manager.System_Int32
End Get
End Property
Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Dim compilation = DirectCast(Me.ContainingType, AnonymousTypeTemplateSymbol).Manager.Compilation
AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute())
End Sub
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
End Class
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.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
Partial Friend NotInheritable Class AnonymousTypeManager
Partial Private NotInheritable Class AnonymousTypeGetHashCodeMethodSymbol
Inherits SynthesizedRegularMethodBase
Public Sub New(container As AnonymousTypeTemplateSymbol)
MyBase.New(VisualBasicSyntaxTree.Dummy.GetRoot(), container, WellKnownMemberNames.ObjectGetHashCode)
End Sub
Private ReadOnly Property AnonymousType As AnonymousTypeTemplateSymbol
Get
Return DirectCast(Me.m_containingType, AnonymousTypeTemplateSymbol)
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property OverriddenMethod As MethodSymbol
Get
Return Me.AnonymousType.Manager.System_Object__GetHashCode
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Public
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return AnonymousType.Manager.System_Int32
End Get
End Property
Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData))
MyBase.AddSynthesizedAttributes(compilationState, attributes)
Dim compilation = DirectCast(Me.ContainingType, AnonymousTypeTemplateSymbol).Manager.Compilation
AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute())
End Sub
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ObjectWriterExtensions.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 Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class ObjectWriterExtensions
{
public static void WriteArray<T>(this ObjectWriter writer, ImmutableArray<T> values, Action<ObjectWriter, T> write)
{
writer.WriteInt32(values.Length);
foreach (var val in values)
write(writer, val);
}
}
internal static class ObjectReaderExtensions
{
public static ImmutableArray<T> ReadArray<T>(this ObjectReader reader, Func<ObjectReader, T> read)
{
var length = reader.ReadInt32();
using var _ = ArrayBuilder<T>.GetInstance(length, out var builder);
for (var i = 0; i < length; i++)
builder.Add(read(reader));
return builder.ToImmutable();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class ObjectWriterExtensions
{
public static void WriteArray<T>(this ObjectWriter writer, ImmutableArray<T> values, Action<ObjectWriter, T> write)
{
writer.WriteInt32(values.Length);
foreach (var val in values)
write(writer, val);
}
}
internal static class ObjectReaderExtensions
{
public static ImmutableArray<T> ReadArray<T>(this ObjectReader reader, Func<ObjectReader, T> read)
{
var length = reader.ReadInt32();
using var _ = ArrayBuilder<T>.GetInstance(length, out var builder);
for (var i = 0; i < length; i++)
builder.Add(read(reader));
return builder.ToImmutable();
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/MockHierarchy.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.VisualStudio.Shell.Interop
Imports Microsoft.VisualStudio.OLE.Interop
Imports System.Runtime.InteropServices
Imports Microsoft.VisualStudio.Shell
Imports Roslyn.Utilities
Imports System.IO
Imports Moq
Imports Microsoft.VisualStudio.LanguageServices.ProjectSystem
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework
Public NotInheritable Class MockHierarchy
Implements IVsHierarchy
Implements IVsProject3
Implements IVsAggregatableProject
Implements IVsBuildPropertyStorage
Public Shared ReadOnly ReferencesNodeItemId As UInteger = 123456
Private _projectName As String
Private _projectBinPath As String
Private _maxSupportedLangVer As String
Private _runAnalyzers As String
Private _runAnalyzersDuringLiveAnalysis As String
Private ReadOnly _projectRefPath As String
Private ReadOnly _projectCapabilities As String
Private ReadOnly _projectMock As Mock(Of EnvDTE.Project) = New Mock(Of EnvDTE.Project)(MockBehavior.Strict)
Private ReadOnly _eventSinks As New Dictionary(Of UInteger, IVsHierarchyEvents)
Private ReadOnly _hierarchyItems As New Dictionary(Of UInteger, String)
Public Sub New(projectName As String,
projectFilePath As String,
projectBinPath As String,
projectRefPath As String,
projectCapabilities As String)
_projectName = projectName
_projectBinPath = projectBinPath
_projectRefPath = projectRefPath
_projectCapabilities = projectCapabilities
_hierarchyItems.Add(CType(VSConstants.VSITEMID.Root, UInteger), projectFilePath)
End Sub
Public Sub RenameProject(projectName As String)
If _projectName = projectName Then
Return
End If
_projectName = projectName
For Each sink In _eventSinks.Values
sink.OnPropertyChanged(VSConstants.VSITEMID.Root, __VSHPROPID.VSHPROPID_Name, 0)
Next
End Sub
Public Function AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject3.AddItem
_hierarchyItems.Add(itemidLoc, pszItemName)
Return VSConstants.S_OK
End Function
Public Function AddItemWithSpecific(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSSPECIFICEDITORFLAGS")> grfEditorFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject3.AddItemWithSpecific
_hierarchyItems.Add(itemidLoc, pszItemName)
Return VSConstants.S_OK
End Function
Public Function AdviseHierarchyEvents(pEventSink As IVsHierarchyEvents, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")> ByRef pdwCookie As UInteger) As Integer Implements IVsHierarchy.AdviseHierarchyEvents
pdwCookie = _eventSinks.Keys.Concat({0}).Max() + 1UI
_eventSinks.Add(pdwCookie, pEventSink)
Return VSConstants.S_OK
End Function
Public Function Close() As Integer Implements IVsHierarchy.Close
_hierarchyItems.Clear()
Return VSConstants.S_OK
End Function
Public Function GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject3.GenerateUniqueItemName
Throw New NotImplementedException()
End Function
Public Function GetCanonicalName(itemid As UInteger, ByRef pbstrName As String) As Integer Implements IVsHierarchy.GetCanonicalName
If _hierarchyItems.TryGetValue(itemid, pbstrName) Then
Return VSConstants.S_OK
Else
Return VSConstants.E_FAIL
End If
End Function
Public Function GetGuidProperty(itemid As UInteger, propid As Integer, ByRef pguid As Guid) As Integer Implements IVsHierarchy.GetGuidProperty
If itemid = VSConstants.VSITEMID_ROOT And propid = CType(__VSHPROPID.VSHPROPID_ProjectIDGuid, Integer) Then
pguid = Guid.NewGuid()
Return VSConstants.S_OK
End If
Throw New NotImplementedException()
End Function
Public Function GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject3.GetItemContext
Throw New NotImplementedException()
End Function
Public Function GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject3.GetMkDocument
_hierarchyItems.TryGetValue(itemid, pbstrMkDocument)
Return VSConstants.S_OK
End Function
Public Function GetNestedHierarchy(itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFIID")> ByRef iidHierarchyNested As Guid, ByRef ppHierarchyNested As IntPtr, ByRef pitemidNested As UInteger) As Integer Implements IVsHierarchy.GetNestedHierarchy
Throw New NotImplementedException()
End Function
Public Function GetProperty(itemid As UInteger, propid As Integer, ByRef pvar As Object) As Integer Implements IVsHierarchy.GetProperty
If propid = __VSHPROPID.VSHPROPID_ProjectName Then
pvar = _projectName
Return VSConstants.S_OK
ElseIf propid = __VSHPROPID5.VSHPROPID_ProjectCapabilities Then
pvar = _projectCapabilities
Return VSConstants.S_OK
ElseIf propid = __VSHPROPID7.VSHPROPID_ProjectTreeCapabilities Then
If itemid = ReferencesNodeItemId Then
pvar = "References"
Return VSConstants.S_OK
End If
ElseIf propid = __VSHPROPID.VSHPROPID_ExtObject Then
Dim projectItemMock As Mock(Of EnvDTE.ProjectItem) = New Mock(Of EnvDTE.ProjectItem)(MockBehavior.Strict)
projectItemMock.SetupGet(Function(m) m.ContainingProject).Returns(_projectMock.Object)
projectItemMock.Setup(Function(m) m.FileNames(1)).Returns(_hierarchyItems(itemid))
pvar = projectItemMock.Object
Return VSConstants.S_OK
End If
Return VSConstants.E_NOTIMPL
End Function
Public Function GetSite(ByRef ppSP As IServiceProvider) As Integer Implements IVsHierarchy.GetSite
Throw New NotImplementedException()
End Function
Public Function IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject3.IsDocumentInProject
pfFound = 0
For Each kvp In _hierarchyItems
If kvp.Value = pszMkDocument Then
pfFound = 1
pitemid = kvp.Key
Exit For
End If
Next
Return VSConstants.S_OK
End Function
Public Function OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.OpenItem
Throw New NotImplementedException()
End Function
Public Function OpenItemWithSpecific(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSSPECIFICEDITORFLAGS")> grfEditorFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.OpenItemWithSpecific
Throw New NotImplementedException()
End Function
Public Function ParseCanonicalName(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszName As String, ByRef pitemid As UInteger) As Integer Implements IVsHierarchy.ParseCanonicalName
For Each kvp In _hierarchyItems
If kvp.Value = pszName Then
pitemid = kvp.Key
Exit For
End If
Next
Return VSConstants.S_OK
End Function
Public Function QueryClose(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfCanClose As Integer) As Integer Implements IVsHierarchy.QueryClose
Throw New NotImplementedException()
End Function
Public Function RemoveItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")> dwReserved As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfResult As Integer) As Integer Implements IVsProject3.RemoveItem
_hierarchyItems.Remove(itemid)
Return VSConstants.S_OK
End Function
Public Function ReopenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.ReopenItem
Throw New NotImplementedException()
End Function
Public Function SetGuidProperty(itemid As UInteger, propid As Integer, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguid As Guid) As Integer Implements IVsHierarchy.SetGuidProperty
Throw New NotImplementedException()
End Function
Public Function SetProperty(itemid As UInteger, propid As Integer, var As Object) As Integer Implements IVsHierarchy.SetProperty
If propid = __VSHPROPID.VSHPROPID_ProjectName Then
_projectName = If(TryCast(var, String), _projectName)
Return VSConstants.S_OK
End If
Throw New NotImplementedException()
End Function
Public Function SetSite(psp As IServiceProvider) As Integer Implements IVsHierarchy.SetSite
Throw New NotImplementedException()
End Function
Public Function TransferItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocumentOld As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocumentNew As String, punkWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.TransferItem
For Each kvp In _hierarchyItems
If kvp.Value = pszMkDocumentOld Then
_hierarchyItems(kvp.Key) = pszMkDocumentNew
Exit For
End If
Next
Return VSConstants.S_OK
End Function
Public Function UnadviseHierarchyEvents(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")> dwCookie As UInteger) As Integer Implements IVsHierarchy.UnadviseHierarchyEvents
If Not _eventSinks.Remove(dwCookie) Then
Throw New InvalidOperationException("The cookie was not subscribed.")
End If
Return VSConstants.S_OK
End Function
Public Function Unused0() As Integer Implements IVsHierarchy.Unused0
Throw New NotImplementedException()
End Function
Public Function Unused1() As Integer Implements IVsHierarchy.Unused1
Throw New NotImplementedException()
End Function
Public Function Unused2() As Integer Implements IVsHierarchy.Unused2
Throw New NotImplementedException()
End Function
Public Function Unused3() As Integer Implements IVsHierarchy.Unused3
Throw New NotImplementedException()
End Function
Public Function Unused4() As Integer Implements IVsHierarchy.Unused4
Throw New NotImplementedException()
End Function
Private Function IVsProject2_AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject2.AddItem
Throw New NotImplementedException()
End Function
Private Function IVsProject2_GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject2.GenerateUniqueItemName
Throw New NotImplementedException()
End Function
Private Function IVsProject2_GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject2.GetItemContext
Throw New NotImplementedException()
End Function
Private Function IVsProject2_GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject2.GetMkDocument
Throw New NotImplementedException()
End Function
Private Function IVsProject2_IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject2.IsDocumentInProject
Throw New NotImplementedException()
End Function
Private Function IVsProject2_OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject2.OpenItem
Throw New NotImplementedException()
End Function
Private Function IVsProject2_RemoveItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")> dwReserved As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfResult As Integer) As Integer Implements IVsProject2.RemoveItem
Throw New NotImplementedException()
End Function
Private Function IVsProject2_ReopenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject2.ReopenItem
Throw New NotImplementedException()
End Function
Private Function IVsProject_AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject.AddItem
Throw New NotImplementedException()
End Function
Private Function IVsProject_GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject.GenerateUniqueItemName
Throw New NotImplementedException()
End Function
Private Function IVsProject_GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject.GetItemContext
Throw New NotImplementedException()
End Function
Private Function IVsProject_GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject.GetMkDocument
Throw New NotImplementedException()
End Function
Private Function IVsProject_IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject.IsDocumentInProject
Throw New NotImplementedException()
End Function
Private Function IVsProject_OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject.OpenItem
Throw New NotImplementedException()
End Function
Public Function SetInnerProject(punkInner As Object) As Integer Implements IVsAggregatableProject.SetInnerProject
Throw New NotImplementedException()
End Function
Public Function InitializeForOuter(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszFilename As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszLocation As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszName As String, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCREATEPROJFLAGS")> grfCreateFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFIID")> ByRef iidProject As Guid, ByRef ppvProject As IntPtr, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfCanceled As Integer) As Integer Implements IVsAggregatableProject.InitializeForOuter
Throw New NotImplementedException()
End Function
Public Function OnAggregationComplete() As Integer Implements IVsAggregatableProject.OnAggregationComplete
Throw New NotImplementedException()
End Function
Public Function GetAggregateProjectTypeGuids(ByRef pbstrProjTypeGuids As String) As Integer Implements IVsAggregatableProject.GetAggregateProjectTypeGuids
If _projectCapabilities = "VB" Then
pbstrProjTypeGuids = Guids.VisualBasicProjectIdString
Return VSConstants.S_OK
ElseIf _projectCapabilities = "CSharp" Then
pbstrProjTypeGuids = Guids.CSharpProjectIdString
Return VSConstants.S_OK
End If
Throw New NotImplementedException()
End Function
Public Function SetAggregateProjectTypeGuids(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> lpstrProjTypeGuids As String) As Integer Implements IVsAggregatableProject.SetAggregateProjectTypeGuids
Throw New NotImplementedException()
End Function
Public Function GetPropertyValue(pszPropName As String, pszConfigName As String, storage As UInteger, ByRef pbstrPropValue As String) As Integer Implements IVsBuildPropertyStorage.GetPropertyValue
If pszPropName = "OutDir" Then
pbstrPropValue = _projectBinPath
Return VSConstants.S_OK
ElseIf pszPropName = "TargetFileName" Then
pbstrPropValue = PathUtilities.ChangeExtension(_projectName, "dll")
Return VSConstants.S_OK
ElseIf pszPropName = "TargetRefPath" Then
pbstrPropValue = _projectRefPath
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.MaxSupportedLangVersion Then
pbstrPropValue = _maxSupportedLangVer
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzers Then
pbstrPropValue = _runAnalyzers
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis Then
pbstrPropValue = _runAnalyzersDuringLiveAnalysis
Return VSConstants.S_OK
End If
Throw New NotSupportedException($"{NameOf(MockHierarchy)}.{NameOf(GetPropertyValue)} does not support reading {pszPropName}.")
End Function
Public Function SetPropertyValue(pszPropName As String, pszConfigName As String, storage As UInteger, pszPropValue As String) As Integer Implements IVsBuildPropertyStorage.SetPropertyValue
If pszPropName = "OutDir" Then
_projectBinPath = pszPropValue
Return VSConstants.S_OK
ElseIf pszPropName = "TargetFileName" Then
_projectName = PathUtilities.GetFileName(pszPropValue, includeExtension:=False)
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.MaxSupportedLangVersion Then
_maxSupportedLangVer = pszPropValue
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzers Then
_runAnalyzers = pszPropValue
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis Then
_runAnalyzersDuringLiveAnalysis = pszPropValue
Return VSConstants.S_OK
End If
Throw New NotImplementedException()
End Function
Public Function RemoveProperty(pszPropName As String, pszConfigName As String, storage As UInteger) As Integer Implements IVsBuildPropertyStorage.RemoveProperty
Throw New NotImplementedException()
End Function
Public Function GetItemAttribute(item As UInteger, pszAttributeName As String, ByRef pbstrAttributeValue As String) As Integer Implements IVsBuildPropertyStorage.GetItemAttribute
Throw New NotImplementedException()
End Function
Public Function SetItemAttribute(item As UInteger, pszAttributeName As String, pszAttributeValue As String) As Integer Implements IVsBuildPropertyStorage.SetItemAttribute
Throw New NotImplementedException()
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.VisualStudio.Shell.Interop
Imports Microsoft.VisualStudio.OLE.Interop
Imports System.Runtime.InteropServices
Imports Microsoft.VisualStudio.Shell
Imports Roslyn.Utilities
Imports System.IO
Imports Moq
Imports Microsoft.VisualStudio.LanguageServices.ProjectSystem
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework
Public NotInheritable Class MockHierarchy
Implements IVsHierarchy
Implements IVsProject3
Implements IVsAggregatableProject
Implements IVsBuildPropertyStorage
Public Shared ReadOnly ReferencesNodeItemId As UInteger = 123456
Private _projectName As String
Private _projectBinPath As String
Private _maxSupportedLangVer As String
Private _runAnalyzers As String
Private _runAnalyzersDuringLiveAnalysis As String
Private ReadOnly _projectRefPath As String
Private ReadOnly _projectCapabilities As String
Private ReadOnly _projectMock As Mock(Of EnvDTE.Project) = New Mock(Of EnvDTE.Project)(MockBehavior.Strict)
Private ReadOnly _eventSinks As New Dictionary(Of UInteger, IVsHierarchyEvents)
Private ReadOnly _hierarchyItems As New Dictionary(Of UInteger, String)
Public Sub New(projectName As String,
projectFilePath As String,
projectBinPath As String,
projectRefPath As String,
projectCapabilities As String)
_projectName = projectName
_projectBinPath = projectBinPath
_projectRefPath = projectRefPath
_projectCapabilities = projectCapabilities
_hierarchyItems.Add(CType(VSConstants.VSITEMID.Root, UInteger), projectFilePath)
End Sub
Public Sub RenameProject(projectName As String)
If _projectName = projectName Then
Return
End If
_projectName = projectName
For Each sink In _eventSinks.Values
sink.OnPropertyChanged(VSConstants.VSITEMID.Root, __VSHPROPID.VSHPROPID_Name, 0)
Next
End Sub
Public Function AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject3.AddItem
_hierarchyItems.Add(itemidLoc, pszItemName)
Return VSConstants.S_OK
End Function
Public Function AddItemWithSpecific(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSSPECIFICEDITORFLAGS")> grfEditorFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject3.AddItemWithSpecific
_hierarchyItems.Add(itemidLoc, pszItemName)
Return VSConstants.S_OK
End Function
Public Function AdviseHierarchyEvents(pEventSink As IVsHierarchyEvents, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")> ByRef pdwCookie As UInteger) As Integer Implements IVsHierarchy.AdviseHierarchyEvents
pdwCookie = _eventSinks.Keys.Concat({0}).Max() + 1UI
_eventSinks.Add(pdwCookie, pEventSink)
Return VSConstants.S_OK
End Function
Public Function Close() As Integer Implements IVsHierarchy.Close
_hierarchyItems.Clear()
Return VSConstants.S_OK
End Function
Public Function GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject3.GenerateUniqueItemName
Throw New NotImplementedException()
End Function
Public Function GetCanonicalName(itemid As UInteger, ByRef pbstrName As String) As Integer Implements IVsHierarchy.GetCanonicalName
If _hierarchyItems.TryGetValue(itemid, pbstrName) Then
Return VSConstants.S_OK
Else
Return VSConstants.E_FAIL
End If
End Function
Public Function GetGuidProperty(itemid As UInteger, propid As Integer, ByRef pguid As Guid) As Integer Implements IVsHierarchy.GetGuidProperty
If itemid = VSConstants.VSITEMID_ROOT And propid = CType(__VSHPROPID.VSHPROPID_ProjectIDGuid, Integer) Then
pguid = Guid.NewGuid()
Return VSConstants.S_OK
End If
Throw New NotImplementedException()
End Function
Public Function GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject3.GetItemContext
Throw New NotImplementedException()
End Function
Public Function GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject3.GetMkDocument
_hierarchyItems.TryGetValue(itemid, pbstrMkDocument)
Return VSConstants.S_OK
End Function
Public Function GetNestedHierarchy(itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFIID")> ByRef iidHierarchyNested As Guid, ByRef ppHierarchyNested As IntPtr, ByRef pitemidNested As UInteger) As Integer Implements IVsHierarchy.GetNestedHierarchy
Throw New NotImplementedException()
End Function
Public Function GetProperty(itemid As UInteger, propid As Integer, ByRef pvar As Object) As Integer Implements IVsHierarchy.GetProperty
If propid = __VSHPROPID.VSHPROPID_ProjectName Then
pvar = _projectName
Return VSConstants.S_OK
ElseIf propid = __VSHPROPID5.VSHPROPID_ProjectCapabilities Then
pvar = _projectCapabilities
Return VSConstants.S_OK
ElseIf propid = __VSHPROPID7.VSHPROPID_ProjectTreeCapabilities Then
If itemid = ReferencesNodeItemId Then
pvar = "References"
Return VSConstants.S_OK
End If
ElseIf propid = __VSHPROPID.VSHPROPID_ExtObject Then
Dim projectItemMock As Mock(Of EnvDTE.ProjectItem) = New Mock(Of EnvDTE.ProjectItem)(MockBehavior.Strict)
projectItemMock.SetupGet(Function(m) m.ContainingProject).Returns(_projectMock.Object)
projectItemMock.Setup(Function(m) m.FileNames(1)).Returns(_hierarchyItems(itemid))
pvar = projectItemMock.Object
Return VSConstants.S_OK
End If
Return VSConstants.E_NOTIMPL
End Function
Public Function GetSite(ByRef ppSP As IServiceProvider) As Integer Implements IVsHierarchy.GetSite
Throw New NotImplementedException()
End Function
Public Function IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject3.IsDocumentInProject
pfFound = 0
For Each kvp In _hierarchyItems
If kvp.Value = pszMkDocument Then
pfFound = 1
pitemid = kvp.Key
Exit For
End If
Next
Return VSConstants.S_OK
End Function
Public Function OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.OpenItem
Throw New NotImplementedException()
End Function
Public Function OpenItemWithSpecific(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSSPECIFICEDITORFLAGS")> grfEditorFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.OpenItemWithSpecific
Throw New NotImplementedException()
End Function
Public Function ParseCanonicalName(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszName As String, ByRef pitemid As UInteger) As Integer Implements IVsHierarchy.ParseCanonicalName
For Each kvp In _hierarchyItems
If kvp.Value = pszName Then
pitemid = kvp.Key
Exit For
End If
Next
Return VSConstants.S_OK
End Function
Public Function QueryClose(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfCanClose As Integer) As Integer Implements IVsHierarchy.QueryClose
Throw New NotImplementedException()
End Function
Public Function RemoveItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")> dwReserved As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfResult As Integer) As Integer Implements IVsProject3.RemoveItem
_hierarchyItems.Remove(itemid)
Return VSConstants.S_OK
End Function
Public Function ReopenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.ReopenItem
Throw New NotImplementedException()
End Function
Public Function SetGuidProperty(itemid As UInteger, propid As Integer, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguid As Guid) As Integer Implements IVsHierarchy.SetGuidProperty
Throw New NotImplementedException()
End Function
Public Function SetProperty(itemid As UInteger, propid As Integer, var As Object) As Integer Implements IVsHierarchy.SetProperty
If propid = __VSHPROPID.VSHPROPID_ProjectName Then
_projectName = If(TryCast(var, String), _projectName)
Return VSConstants.S_OK
End If
Throw New NotImplementedException()
End Function
Public Function SetSite(psp As IServiceProvider) As Integer Implements IVsHierarchy.SetSite
Throw New NotImplementedException()
End Function
Public Function TransferItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocumentOld As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocumentNew As String, punkWindowFrame As IVsWindowFrame) As Integer Implements IVsProject3.TransferItem
For Each kvp In _hierarchyItems
If kvp.Value = pszMkDocumentOld Then
_hierarchyItems(kvp.Key) = pszMkDocumentNew
Exit For
End If
Next
Return VSConstants.S_OK
End Function
Public Function UnadviseHierarchyEvents(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")> dwCookie As UInteger) As Integer Implements IVsHierarchy.UnadviseHierarchyEvents
If Not _eventSinks.Remove(dwCookie) Then
Throw New InvalidOperationException("The cookie was not subscribed.")
End If
Return VSConstants.S_OK
End Function
Public Function Unused0() As Integer Implements IVsHierarchy.Unused0
Throw New NotImplementedException()
End Function
Public Function Unused1() As Integer Implements IVsHierarchy.Unused1
Throw New NotImplementedException()
End Function
Public Function Unused2() As Integer Implements IVsHierarchy.Unused2
Throw New NotImplementedException()
End Function
Public Function Unused3() As Integer Implements IVsHierarchy.Unused3
Throw New NotImplementedException()
End Function
Public Function Unused4() As Integer Implements IVsHierarchy.Unused4
Throw New NotImplementedException()
End Function
Private Function IVsProject2_AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject2.AddItem
Throw New NotImplementedException()
End Function
Private Function IVsProject2_GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject2.GenerateUniqueItemName
Throw New NotImplementedException()
End Function
Private Function IVsProject2_GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject2.GetItemContext
Throw New NotImplementedException()
End Function
Private Function IVsProject2_GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject2.GetMkDocument
Throw New NotImplementedException()
End Function
Private Function IVsProject2_IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject2.IsDocumentInProject
Throw New NotImplementedException()
End Function
Private Function IVsProject2_OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject2.OpenItem
Throw New NotImplementedException()
End Function
Private Function IVsProject2_RemoveItem(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")> dwReserved As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfResult As Integer) As Integer Implements IVsProject2.RemoveItem
Throw New NotImplementedException()
End Function
Private Function IVsProject2_ReopenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidEditorType As Guid, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszPhysicalView As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject2.ReopenItem
Throw New NotImplementedException()
End Function
Private Function IVsProject_AddItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDITEMOPERATION")> dwAddItemOperation As VSADDITEMOPERATION, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszItemName As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.ULONG")> cFilesToOpen As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> rgpszFilesToOpen() As String, hwndDlgOwner As IntPtr, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSADDRESULT")> pResult() As VSADDRESULT) As Integer Implements IVsProject.AddItem
Throw New NotImplementedException()
End Function
Private Function IVsProject_GenerateUniqueItemName(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemidLoc As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszExt As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszSuggestedRoot As String, ByRef pbstrItemName As String) As Integer Implements IVsProject.GenerateUniqueItemName
Throw New NotImplementedException()
End Function
Private Function IVsProject_GetItemContext(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef ppSP As IServiceProvider) As Integer Implements IVsProject.GetItemContext
Throw New NotImplementedException()
End Function
Private Function IVsProject_GetMkDocument(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, ByRef pbstrMkDocument As String) As Integer Implements IVsProject.GetMkDocument
Throw New NotImplementedException()
End Function
Private Function IVsProject_IsDocumentInProject(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszMkDocument As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfFound As Integer, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSDOCUMENTPRIORITY")> pdwPriority() As VSDOCUMENTPRIORITY, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> ByRef pitemid As UInteger) As Integer Implements IVsProject.IsDocumentInProject
Throw New NotImplementedException()
End Function
Private Function IVsProject_OpenItem(<ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")> itemid As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFGUID")> ByRef rguidLogicalView As Guid, punkDocDataExisting As IntPtr, ByRef ppWindowFrame As IVsWindowFrame) As Integer Implements IVsProject.OpenItem
Throw New NotImplementedException()
End Function
Public Function SetInnerProject(punkInner As Object) As Integer Implements IVsAggregatableProject.SetInnerProject
Throw New NotImplementedException()
End Function
Public Function InitializeForOuter(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszFilename As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszLocation As String, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> pszName As String, <ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCREATEPROJFLAGS")> grfCreateFlags As UInteger, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.REFIID")> ByRef iidProject As Guid, ByRef ppvProject As IntPtr, <ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")> ByRef pfCanceled As Integer) As Integer Implements IVsAggregatableProject.InitializeForOuter
Throw New NotImplementedException()
End Function
Public Function OnAggregationComplete() As Integer Implements IVsAggregatableProject.OnAggregationComplete
Throw New NotImplementedException()
End Function
Public Function GetAggregateProjectTypeGuids(ByRef pbstrProjTypeGuids As String) As Integer Implements IVsAggregatableProject.GetAggregateProjectTypeGuids
If _projectCapabilities = "VB" Then
pbstrProjTypeGuids = Guids.VisualBasicProjectIdString
Return VSConstants.S_OK
ElseIf _projectCapabilities = "CSharp" Then
pbstrProjTypeGuids = Guids.CSharpProjectIdString
Return VSConstants.S_OK
End If
Throw New NotImplementedException()
End Function
Public Function SetAggregateProjectTypeGuids(<ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCOLESTR")> lpstrProjTypeGuids As String) As Integer Implements IVsAggregatableProject.SetAggregateProjectTypeGuids
Throw New NotImplementedException()
End Function
Public Function GetPropertyValue(pszPropName As String, pszConfigName As String, storage As UInteger, ByRef pbstrPropValue As String) As Integer Implements IVsBuildPropertyStorage.GetPropertyValue
If pszPropName = "OutDir" Then
pbstrPropValue = _projectBinPath
Return VSConstants.S_OK
ElseIf pszPropName = "TargetFileName" Then
pbstrPropValue = PathUtilities.ChangeExtension(_projectName, "dll")
Return VSConstants.S_OK
ElseIf pszPropName = "TargetRefPath" Then
pbstrPropValue = _projectRefPath
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.MaxSupportedLangVersion Then
pbstrPropValue = _maxSupportedLangVer
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzers Then
pbstrPropValue = _runAnalyzers
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis Then
pbstrPropValue = _runAnalyzersDuringLiveAnalysis
Return VSConstants.S_OK
End If
Throw New NotSupportedException($"{NameOf(MockHierarchy)}.{NameOf(GetPropertyValue)} does not support reading {pszPropName}.")
End Function
Public Function SetPropertyValue(pszPropName As String, pszConfigName As String, storage As UInteger, pszPropValue As String) As Integer Implements IVsBuildPropertyStorage.SetPropertyValue
If pszPropName = "OutDir" Then
_projectBinPath = pszPropValue
Return VSConstants.S_OK
ElseIf pszPropName = "TargetFileName" Then
_projectName = PathUtilities.GetFileName(pszPropValue, includeExtension:=False)
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.MaxSupportedLangVersion Then
_maxSupportedLangVer = pszPropValue
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzers Then
_runAnalyzers = pszPropValue
Return VSConstants.S_OK
ElseIf pszPropName = AdditionalPropertyNames.RunAnalyzersDuringLiveAnalysis Then
_runAnalyzersDuringLiveAnalysis = pszPropValue
Return VSConstants.S_OK
End If
Throw New NotImplementedException()
End Function
Public Function RemoveProperty(pszPropName As String, pszConfigName As String, storage As UInteger) As Integer Implements IVsBuildPropertyStorage.RemoveProperty
Throw New NotImplementedException()
End Function
Public Function GetItemAttribute(item As UInteger, pszAttributeName As String, ByRef pbstrAttributeValue As String) As Integer Implements IVsBuildPropertyStorage.GetItemAttribute
Throw New NotImplementedException()
End Function
Public Function SetItemAttribute(item As UInteger, pszAttributeName As String, pszAttributeValue As String) As Integer Implements IVsBuildPropertyStorage.SetItemAttribute
Throw New NotImplementedException()
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/Core.Wpf/Suggestions/AsyncSuggestedActionsSource.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.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnifiedSuggestions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedActionsSourceProvider
{
private partial class AsyncSuggestedActionsSource : SuggestedActionsSource, ISuggestedActionsSourceExperimental
{
public AsyncSuggestedActionsSource(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider owner,
ITextView textView,
ITextBuffer textBuffer,
ISuggestedActionCategoryRegistryService suggestedActionCategoryRegistry)
: base(threadingContext, owner, textView, textBuffer, suggestedActionCategoryRegistry)
{
}
public async IAsyncEnumerable<SuggestedActionSet> GetSuggestedActionsAsync(
ISuggestedActionCategorySet requestedActionCategories,
SnapshotSpan range,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
AssertIsForeground();
using var state = SourceState.TryAddReference();
if (state is null)
yield break;
var workspace = state.Target.Workspace;
if (workspace is null)
yield break;
var selection = TryGetCodeRefactoringSelection(state, range);
await workspace.Services.GetRequiredService<IWorkspaceStatusService>().WaitUntilFullyLoadedAsync(cancellationToken).ConfigureAwait(false);
using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActionsAsync, cancellationToken))
{
var document = range.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document is null)
yield break;
// Compute and return the high pri set of fixes and refactorings first so the user
// can act on them immediately without waiting on the regular set.
var highPriSet = GetCodeFixesAndRefactoringsAsync(
state, requestedActionCategories, document, range, selection, _ => null,
CodeActionRequestPriority.High, cancellationToken).WithCancellation(cancellationToken).ConfigureAwait(false);
await foreach (var set in highPriSet)
yield return set;
var lowPriSet = GetCodeFixesAndRefactoringsAsync(
state, requestedActionCategories, document, range, selection, _ => null,
CodeActionRequestPriority.Normal, cancellationToken).WithCancellation(cancellationToken).ConfigureAwait(false);
await foreach (var set in lowPriSet)
yield return set;
}
}
private async IAsyncEnumerable<SuggestedActionSet> GetCodeFixesAndRefactoringsAsync(
ReferenceCountedDisposable<State> state,
ISuggestedActionCategorySet requestedActionCategories,
Document document,
SnapshotSpan range,
TextSpan? selection,
Func<string, IDisposable?> addOperationScope,
CodeActionRequestPriority priority,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetRequiredService<ITextBufferSupportsFeatureService>();
var fixesTask = GetCodeFixesAsync(
state, supportsFeatureService, requestedActionCategories, workspace, document, range,
addOperationScope, priority, isBlocking: false, cancellationToken);
var refactoringsTask = GetRefactoringsAsync(
state, supportsFeatureService, requestedActionCategories, workspace, document, selection,
addOperationScope, priority, isBlocking: false, cancellationToken);
if (priority == CodeActionRequestPriority.High)
{
// in a high pri scenario, return data as soon as possible so that the user can interact with them.
// this is especially important for state-machine oriented refactorings (like rename) where the user
// should always have access to them effectively synchronously.
var firstTask = await Task.WhenAny(fixesTask, refactoringsTask).ConfigureAwait(false);
var secondTask = firstTask == fixesTask ? refactoringsTask : fixesTask;
var orderedTasks = new[] { firstTask, secondTask };
foreach (var task in orderedTasks)
{
if (task == fixesTask)
{
var fixes = await fixesTask.ConfigureAwait(false);
foreach (var set in ConvertToSuggestedActionSets(state, selection, fixes, ImmutableArray<UnifiedSuggestedActionSet>.Empty))
yield return set;
}
else
{
Contract.ThrowIfFalse(task == refactoringsTask);
var refactorings = await refactoringsTask.ConfigureAwait(false);
foreach (var set in ConvertToSuggestedActionSets(state, selection, ImmutableArray<UnifiedSuggestedActionSet>.Empty, refactorings))
yield return set;
}
}
}
else
{
var actionsArray = await Task.WhenAll(fixesTask, refactoringsTask).ConfigureAwait(false);
foreach (var set in ConvertToSuggestedActionSets(state, selection, fixes: actionsArray[0], refactorings: actionsArray[1]))
yield return 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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnifiedSuggestions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
internal partial class SuggestedActionsSourceProvider
{
private partial class AsyncSuggestedActionsSource : SuggestedActionsSource, ISuggestedActionsSourceExperimental
{
public AsyncSuggestedActionsSource(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider owner,
ITextView textView,
ITextBuffer textBuffer,
ISuggestedActionCategoryRegistryService suggestedActionCategoryRegistry)
: base(threadingContext, owner, textView, textBuffer, suggestedActionCategoryRegistry)
{
}
public async IAsyncEnumerable<SuggestedActionSet> GetSuggestedActionsAsync(
ISuggestedActionCategorySet requestedActionCategories,
SnapshotSpan range,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
AssertIsForeground();
using var state = SourceState.TryAddReference();
if (state is null)
yield break;
var workspace = state.Target.Workspace;
if (workspace is null)
yield break;
var selection = TryGetCodeRefactoringSelection(state, range);
await workspace.Services.GetRequiredService<IWorkspaceStatusService>().WaitUntilFullyLoadedAsync(cancellationToken).ConfigureAwait(false);
using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActionsAsync, cancellationToken))
{
var document = range.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document is null)
yield break;
// Compute and return the high pri set of fixes and refactorings first so the user
// can act on them immediately without waiting on the regular set.
var highPriSet = GetCodeFixesAndRefactoringsAsync(
state, requestedActionCategories, document, range, selection, _ => null,
CodeActionRequestPriority.High, cancellationToken).WithCancellation(cancellationToken).ConfigureAwait(false);
await foreach (var set in highPriSet)
yield return set;
var lowPriSet = GetCodeFixesAndRefactoringsAsync(
state, requestedActionCategories, document, range, selection, _ => null,
CodeActionRequestPriority.Normal, cancellationToken).WithCancellation(cancellationToken).ConfigureAwait(false);
await foreach (var set in lowPriSet)
yield return set;
}
}
private async IAsyncEnumerable<SuggestedActionSet> GetCodeFixesAndRefactoringsAsync(
ReferenceCountedDisposable<State> state,
ISuggestedActionCategorySet requestedActionCategories,
Document document,
SnapshotSpan range,
TextSpan? selection,
Func<string, IDisposable?> addOperationScope,
CodeActionRequestPriority priority,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetRequiredService<ITextBufferSupportsFeatureService>();
var fixesTask = GetCodeFixesAsync(
state, supportsFeatureService, requestedActionCategories, workspace, document, range,
addOperationScope, priority, isBlocking: false, cancellationToken);
var refactoringsTask = GetRefactoringsAsync(
state, supportsFeatureService, requestedActionCategories, workspace, document, selection,
addOperationScope, priority, isBlocking: false, cancellationToken);
if (priority == CodeActionRequestPriority.High)
{
// in a high pri scenario, return data as soon as possible so that the user can interact with them.
// this is especially important for state-machine oriented refactorings (like rename) where the user
// should always have access to them effectively synchronously.
var firstTask = await Task.WhenAny(fixesTask, refactoringsTask).ConfigureAwait(false);
var secondTask = firstTask == fixesTask ? refactoringsTask : fixesTask;
var orderedTasks = new[] { firstTask, secondTask };
foreach (var task in orderedTasks)
{
if (task == fixesTask)
{
var fixes = await fixesTask.ConfigureAwait(false);
foreach (var set in ConvertToSuggestedActionSets(state, selection, fixes, ImmutableArray<UnifiedSuggestedActionSet>.Empty))
yield return set;
}
else
{
Contract.ThrowIfFalse(task == refactoringsTask);
var refactorings = await refactoringsTask.ConfigureAwait(false);
foreach (var set in ConvertToSuggestedActionSets(state, selection, ImmutableArray<UnifiedSuggestedActionSet>.Empty, refactorings))
yield return set;
}
}
}
else
{
var actionsArray = await Task.WhenAll(fixesTask, refactoringsTask).ConfigureAwait(false);
foreach (var set in ConvertToSuggestedActionSets(state, selection, fixes: actionsArray[0], refactorings: actionsArray[1]))
yield return set;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/CSharp/Portable/Formatting/CSharpFormattingInteractionService.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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Indentation;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
[ExportLanguageService(typeof(IFormattingInteractionService), LanguageNames.CSharp), Shared]
internal partial class CSharpFormattingInteractionService : IFormattingInteractionService
{
// All the characters that might potentially trigger formatting when typed
private readonly char[] _supportedChars = ";{}#nte:)".ToCharArray();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpFormattingInteractionService()
{
}
public bool SupportsFormatDocument => true;
public bool SupportsFormatOnPaste => true;
public bool SupportsFormatSelection => true;
public bool SupportsFormatOnReturn => false;
public bool SupportsFormattingOnTypedCharacter(Document document, char ch)
{
// Performance: This method checks several options to determine if we should do smart
// indent, none of which are controlled by editorconfig. Instead of calling
// document.GetOptionsAsync we can use the Workspace's global options and thus save the
// work of attempting to read in the editorconfig file.
var options = document.Project.Solution.Workspace.Options;
var smartIndentOn = options.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) == FormattingOptions.IndentStyle.Smart;
// We consider the proper placement of a close curly or open curly when it is typed at
// the start of the line to be a smart-indentation operation. As such, even if "format
// on typing" is off, if "smart indent" is on, we'll still format this. (However, we
// won't touch anything else in the block this close curly belongs to.).
//
// See extended comment in GetFormattingChangesAsync for more details on this.
if (smartIndentOn)
{
if (ch == '{' || ch == '}')
{
return true;
}
}
// If format-on-typing is not on, then we don't support formatting on any other characters.
var autoFormattingOnTyping = options.GetOption(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp);
if (!autoFormattingOnTyping)
{
return false;
}
if (ch == '}' && !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp))
{
return false;
}
if (ch == ';' && !options.GetOption(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp))
{
return false;
}
// don't auto format after these keys if smart indenting is not on.
if ((ch == '#' || ch == 'n') && !smartIndentOn)
{
return false;
}
return _supportedChars.Contains(ch);
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(
Document document,
TextSpan? textSpan,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var span = textSpan ?? new TextSpan(0, root.FullSpan.Length);
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, span);
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: true, cancellationToken: cancellationToken).ConfigureAwait(false);
}
return Formatter.GetFormattedTextChanges(root,
SpecializedCollections.SingletonEnumerable(formattingSpan),
document.Project.Solution.Workspace, options, cancellationToken).ToImmutableArray();
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesOnPasteAsync(
Document document,
TextSpan textSpan,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, textSpan);
var service = document.GetLanguageService<ISyntaxFormattingService>();
if (service == null)
{
return ImmutableArray<TextChange>.Empty;
}
var rules = new List<AbstractFormattingRule>() { new PasteFormattingRule() };
rules.AddRange(service.GetDefaultFormattingRules());
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
return Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(formattingSpan), document.Project.Solution.Workspace, options, rules, cancellationToken).ToImmutableArray();
}
private static IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document, int position, SyntaxToken tokenBeforeCaret)
{
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
return formattingRuleFactory.CreateRule(document, position).Concat(GetTypingRules(tokenBeforeCaret)).Concat(Formatter.GetDefaultFormattingRules(document));
}
Task<ImmutableArray<TextChange>> IFormattingInteractionService.GetFormattingChangesOnReturnAsync(
Document document, int caretPosition, DocumentOptionSet? documentOptions, CancellationToken cancellationToken)
=> SpecializedTasks.EmptyImmutableArray<TextChange>();
private static async Task<bool> TokenShouldNotFormatOnTypeCharAsync(
SyntaxToken token, CancellationToken cancellationToken)
{
// If the token is a ) we only want to format if it's the close paren
// of a using statement. That way if we have nested usings, the inner
// using will align with the outer one when the user types the close paren.
if (token.IsKind(SyntaxKind.CloseParenToken) && !token.Parent.IsKind(SyntaxKind.UsingStatement))
{
return true;
}
// If the token is a : we only want to format if it's a labeled statement
// or case. When the colon is typed we'll want ot immediately have those
// statements snap to their appropriate indentation level.
if (token.IsKind(SyntaxKind.ColonToken) && !(token.Parent.IsKind(SyntaxKind.LabeledStatement) || token.Parent is SwitchLabelSyntax))
{
return true;
}
// Only format an { if it is the first token on a line. We don't want to
// mess with it if it's inside a line.
if (token.IsKind(SyntaxKind.OpenBraceToken))
{
var text = await token.SyntaxTree!.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (!token.IsFirstTokenOnLine(text))
{
return true;
}
}
return false;
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(
Document document,
char typedChar,
int caretPosition,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
// first, find the token user just typed.
var token = await GetTokenBeforeTheCaretAsync(document, caretPosition, cancellationToken).ConfigureAwait(false);
if (token.IsMissing ||
!ValidSingleOrMultiCharactersTokenKind(typedChar, token.Kind()) ||
token.IsKind(SyntaxKind.EndOfFileToken, SyntaxKind.None))
{
return ImmutableArray<TextChange>.Empty;
}
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formattingRules = GetFormattingRules(document, caretPosition, token);
var service = document.GetLanguageService<ISyntaxFactsService>();
if (service != null && service.IsInNonUserCode(token.SyntaxTree, caretPosition, cancellationToken))
{
return ImmutableArray<TextChange>.Empty;
}
var shouldNotFormat = await TokenShouldNotFormatOnTypeCharAsync(token, cancellationToken).ConfigureAwait(false);
if (shouldNotFormat)
{
return ImmutableArray<TextChange>.Empty;
}
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
// Do not attempt to format on open/close brace if autoformat on close brace feature is
// off, instead just smart indent.
//
// We want this behavior because it's totally reasonable for a user to want to not have
// on automatic formatting because they feel it is too aggressive. However, by default,
// if you have smart-indentation on and are just hitting enter, you'll common have the
// caret placed one indent higher than your current construct. For example, if you have:
//
// if (true)
// $ <-- smart indent will have placed the caret here here.
//
// This is acceptable given that the user may want to just write a simple statement there.
// However, if they start writing `{`, then things should snap over to be:
//
// if (true)
// {
//
// Importantly, this is just an indentation change, no actual 'formatting' is done. We do
// the same with close brace. If you have:
//
// if (...)
// {
// bad . ly ( for (mmated+code) ) ;
// $ <-- smart indent will have placed the care here.
//
// If the user hits `}` then we will properly smart indent the `}` to match the `{`.
// However, we won't touch any of the other code in that block, unlike if we were
// formatting.
var onlySmartIndent =
(token.IsKind(SyntaxKind.CloseBraceToken) && OnlySmartIndentCloseBrace(options)) ||
(token.IsKind(SyntaxKind.OpenBraceToken) && OnlySmartIndentOpenBrace(options));
if (onlySmartIndent)
{
// if we're only doing smart indent, then ignore all edits to this token that occur before
// the span of the token. They're irrelevant and may screw up other code the user doesn't
// want touched.
var tokenEdits = await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false);
return tokenEdits.Where(t => t.Span.Start >= token.FullSpan.Start).ToImmutableArray();
}
// if formatting range fails, do format token one at least
var changes = await FormatRangeAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false);
if (changes.Length > 0)
{
return changes;
}
return (await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false)).ToImmutableArray();
}
private static bool OnlySmartIndentCloseBrace(DocumentOptionSet options)
{
// User does not want auto-formatting (either in general, or for close braces in
// specific). So we only smart indent close braces when typed.
return !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace) ||
!options.GetOption(FormattingOptions2.AutoFormattingOnTyping);
}
private static bool OnlySmartIndentOpenBrace(DocumentOptionSet options)
{
// User does not want auto-formatting . So we only smart indent open braces when typed.
// Note: there is no specific option for controlling formatting on open brace. So we
// don't have the symmetry with OnlySmartIndentCloseBrace.
return !options.GetOption(FormattingOptions2.AutoFormattingOnTyping);
}
private static async Task<SyntaxToken> GetTokenBeforeTheCaretAsync(Document document, int caretPosition, CancellationToken cancellationToken)
{
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var position = Math.Max(0, caretPosition - 1);
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(position, findInsideTrivia: true);
return token;
}
private static async Task<IList<TextChange>> FormatTokenAsync(Document document, OptionSet options, SyntaxToken token, IEnumerable<AbstractFormattingRule> formattingRules, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formatter = CreateSmartTokenFormatter(options, formattingRules, root);
var changes = await formatter.FormatTokenAsync(document.Project.Solution.Workspace, token, cancellationToken).ConfigureAwait(false);
return changes;
}
private static ISmartTokenFormatter CreateSmartTokenFormatter(OptionSet optionSet, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode root)
=> new CSharpSmartTokenFormatter(optionSet, formattingRules, (CompilationUnitSyntax)root);
private static async Task<ImmutableArray<TextChange>> FormatRangeAsync(
Document document,
OptionSet options,
SyntaxToken endToken,
IEnumerable<AbstractFormattingRule> formattingRules,
CancellationToken cancellationToken)
{
if (!IsEndToken(endToken))
{
return ImmutableArray<TextChange>.Empty;
}
var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken);
if (tokenRange == null || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2))
{
return ImmutableArray<TextChange>.Empty;
}
if (IsInvalidTokenKind(tokenRange.Value.Item1) || IsInvalidTokenKind(tokenRange.Value.Item2))
{
return ImmutableArray<TextChange>.Empty;
}
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formatter = new CSharpSmartTokenFormatter(options, formattingRules, (CompilationUnitSyntax)root);
var changes = formatter.FormatRange(document.Project.Solution.Workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, cancellationToken);
return changes.ToImmutableArray();
}
private static IEnumerable<AbstractFormattingRule> GetTypingRules(SyntaxToken tokenBeforeCaret)
{
// Typing introduces several challenges around formatting.
// Historically we've shipped several triggers that cause formatting to happen directly while typing.
// These include formatting of blocks when '}' is typed, formatting of statements when a ';' is typed, formatting of ```case```s when ':' typed, and many other cases.
// However, formatting during typing can potentially cause problems. This is because the surrounding code may not be complete,
// or may otherwise have syntax errors, and thus edits could have unintended consequences.
//
// Because of this, we introduce an extra rule into the set of formatting rules whose purpose is to actually make formatting *more*
// conservative and *less* willing willing to make edits to the tree.
// The primary effect this rule has is to assume that more code is on a single line (and thus should stay that way)
// despite what the tree actually looks like.
//
// It's ok that this is only during formatting that is caused by an edit because that formatting happens
// implicitly and thus has to be more careful, whereas an explicit format-document call only happens on-demand
// and can be more aggressive about what it's doing.
//
//
// For example, say you have the following code.
//
// ```c#
// class C
// {
// int P { get { return
// }
// ```
//
// Hitting ';' after 'return' should ideally only affect the 'return statement' and change it to:
//
// ```c#
// class C
// {
// int P { get { return;
// }
// ```
//
// During a normal format-document call, this is not what would happen.
// Specifically, because the parser will consume the '}' into the accessor,
// it will think the accessor spans multiple lines, and thus should not stay on a single line. This will produce:
//
// ```c#
// class C
// {
// int P
// {
// get
// {
// return;
// }
// ```
//
// Because it's ok for this to format in that fashion if format-document is invoked,
// but should not happen during typing, we insert a specialized rule *only* during typing to try to control this.
// During normal formatting we add 'keep on single line' suppression rules for blocks we find that are on a single line.
// But that won't work since this span is not on a single line:
//
// ```c#
// class C
// {
// int P { get [|{ return;
// }|]
// ```
//
// So, during typing, if we see any parent block is incomplete, we'll assume that
// all our parent blocks are incomplete and we will place the suppression span like so:
//
// ```c#
// class C
// {
// int P { get [|{ return;|]
// }
// ```
//
// This will have the desired effect of keeping these tokens on the same line, but only during typing scenarios.
if (tokenBeforeCaret.Kind() == SyntaxKind.CloseBraceToken ||
tokenBeforeCaret.Kind() == SyntaxKind.EndOfFileToken)
{
return SpecializedCollections.EmptyEnumerable<AbstractFormattingRule>();
}
return SpecializedCollections.SingletonEnumerable(TypingFormattingRule.Instance);
}
private static bool IsEndToken(SyntaxToken endToken)
{
if (endToken.IsKind(SyntaxKind.OpenBraceToken))
{
return false;
}
return true;
}
// We'll autoformat on n, t, e, only if they are the last character of the below
// keywords.
private static bool ValidSingleOrMultiCharactersTokenKind(char typedChar, SyntaxKind kind)
=> typedChar switch
{
'n' => kind == SyntaxKind.RegionKeyword || kind == SyntaxKind.EndRegionKeyword,
't' => kind == SyntaxKind.SelectKeyword,
'e' => kind == SyntaxKind.WhereKeyword,
_ => true,
};
private static bool IsInvalidTokenKind(SyntaxToken token)
{
// invalid token to be formatted
return token.IsKind(SyntaxKind.None) ||
token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
token.IsKind(SyntaxKind.EndOfFileToken);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Indentation;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
[ExportLanguageService(typeof(IFormattingInteractionService), LanguageNames.CSharp), Shared]
internal partial class CSharpFormattingInteractionService : IFormattingInteractionService
{
// All the characters that might potentially trigger formatting when typed
private readonly char[] _supportedChars = ";{}#nte:)".ToCharArray();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpFormattingInteractionService()
{
}
public bool SupportsFormatDocument => true;
public bool SupportsFormatOnPaste => true;
public bool SupportsFormatSelection => true;
public bool SupportsFormatOnReturn => false;
public bool SupportsFormattingOnTypedCharacter(Document document, char ch)
{
// Performance: This method checks several options to determine if we should do smart
// indent, none of which are controlled by editorconfig. Instead of calling
// document.GetOptionsAsync we can use the Workspace's global options and thus save the
// work of attempting to read in the editorconfig file.
var options = document.Project.Solution.Workspace.Options;
var smartIndentOn = options.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) == FormattingOptions.IndentStyle.Smart;
// We consider the proper placement of a close curly or open curly when it is typed at
// the start of the line to be a smart-indentation operation. As such, even if "format
// on typing" is off, if "smart indent" is on, we'll still format this. (However, we
// won't touch anything else in the block this close curly belongs to.).
//
// See extended comment in GetFormattingChangesAsync for more details on this.
if (smartIndentOn)
{
if (ch == '{' || ch == '}')
{
return true;
}
}
// If format-on-typing is not on, then we don't support formatting on any other characters.
var autoFormattingOnTyping = options.GetOption(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp);
if (!autoFormattingOnTyping)
{
return false;
}
if (ch == '}' && !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp))
{
return false;
}
if (ch == ';' && !options.GetOption(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp))
{
return false;
}
// don't auto format after these keys if smart indenting is not on.
if ((ch == '#' || ch == 'n') && !smartIndentOn)
{
return false;
}
return _supportedChars.Contains(ch);
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(
Document document,
TextSpan? textSpan,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var span = textSpan ?? new TextSpan(0, root.FullSpan.Length);
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, span);
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: true, cancellationToken: cancellationToken).ConfigureAwait(false);
}
return Formatter.GetFormattedTextChanges(root,
SpecializedCollections.SingletonEnumerable(formattingSpan),
document.Project.Solution.Workspace, options, cancellationToken).ToImmutableArray();
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesOnPasteAsync(
Document document,
TextSpan textSpan,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(root, textSpan);
var service = document.GetLanguageService<ISyntaxFormattingService>();
if (service == null)
{
return ImmutableArray<TextChange>.Empty;
}
var rules = new List<AbstractFormattingRule>() { new PasteFormattingRule() };
rules.AddRange(service.GetDefaultFormattingRules());
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
return Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(formattingSpan), document.Project.Solution.Workspace, options, rules, cancellationToken).ToImmutableArray();
}
private static IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document, int position, SyntaxToken tokenBeforeCaret)
{
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
return formattingRuleFactory.CreateRule(document, position).Concat(GetTypingRules(tokenBeforeCaret)).Concat(Formatter.GetDefaultFormattingRules(document));
}
Task<ImmutableArray<TextChange>> IFormattingInteractionService.GetFormattingChangesOnReturnAsync(
Document document, int caretPosition, DocumentOptionSet? documentOptions, CancellationToken cancellationToken)
=> SpecializedTasks.EmptyImmutableArray<TextChange>();
private static async Task<bool> TokenShouldNotFormatOnTypeCharAsync(
SyntaxToken token, CancellationToken cancellationToken)
{
// If the token is a ) we only want to format if it's the close paren
// of a using statement. That way if we have nested usings, the inner
// using will align with the outer one when the user types the close paren.
if (token.IsKind(SyntaxKind.CloseParenToken) && !token.Parent.IsKind(SyntaxKind.UsingStatement))
{
return true;
}
// If the token is a : we only want to format if it's a labeled statement
// or case. When the colon is typed we'll want ot immediately have those
// statements snap to their appropriate indentation level.
if (token.IsKind(SyntaxKind.ColonToken) && !(token.Parent.IsKind(SyntaxKind.LabeledStatement) || token.Parent is SwitchLabelSyntax))
{
return true;
}
// Only format an { if it is the first token on a line. We don't want to
// mess with it if it's inside a line.
if (token.IsKind(SyntaxKind.OpenBraceToken))
{
var text = await token.SyntaxTree!.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (!token.IsFirstTokenOnLine(text))
{
return true;
}
}
return false;
}
public async Task<ImmutableArray<TextChange>> GetFormattingChangesAsync(
Document document,
char typedChar,
int caretPosition,
DocumentOptionSet? documentOptions,
CancellationToken cancellationToken)
{
// first, find the token user just typed.
var token = await GetTokenBeforeTheCaretAsync(document, caretPosition, cancellationToken).ConfigureAwait(false);
if (token.IsMissing ||
!ValidSingleOrMultiCharactersTokenKind(typedChar, token.Kind()) ||
token.IsKind(SyntaxKind.EndOfFileToken, SyntaxKind.None))
{
return ImmutableArray<TextChange>.Empty;
}
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formattingRules = GetFormattingRules(document, caretPosition, token);
var service = document.GetLanguageService<ISyntaxFactsService>();
if (service != null && service.IsInNonUserCode(token.SyntaxTree, caretPosition, cancellationToken))
{
return ImmutableArray<TextChange>.Empty;
}
var shouldNotFormat = await TokenShouldNotFormatOnTypeCharAsync(token, cancellationToken).ConfigureAwait(false);
if (shouldNotFormat)
{
return ImmutableArray<TextChange>.Empty;
}
var options = documentOptions;
if (options == null)
{
var inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService<IInferredIndentationService>();
options = await inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, explicitFormat: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
// Do not attempt to format on open/close brace if autoformat on close brace feature is
// off, instead just smart indent.
//
// We want this behavior because it's totally reasonable for a user to want to not have
// on automatic formatting because they feel it is too aggressive. However, by default,
// if you have smart-indentation on and are just hitting enter, you'll common have the
// caret placed one indent higher than your current construct. For example, if you have:
//
// if (true)
// $ <-- smart indent will have placed the caret here here.
//
// This is acceptable given that the user may want to just write a simple statement there.
// However, if they start writing `{`, then things should snap over to be:
//
// if (true)
// {
//
// Importantly, this is just an indentation change, no actual 'formatting' is done. We do
// the same with close brace. If you have:
//
// if (...)
// {
// bad . ly ( for (mmated+code) ) ;
// $ <-- smart indent will have placed the care here.
//
// If the user hits `}` then we will properly smart indent the `}` to match the `{`.
// However, we won't touch any of the other code in that block, unlike if we were
// formatting.
var onlySmartIndent =
(token.IsKind(SyntaxKind.CloseBraceToken) && OnlySmartIndentCloseBrace(options)) ||
(token.IsKind(SyntaxKind.OpenBraceToken) && OnlySmartIndentOpenBrace(options));
if (onlySmartIndent)
{
// if we're only doing smart indent, then ignore all edits to this token that occur before
// the span of the token. They're irrelevant and may screw up other code the user doesn't
// want touched.
var tokenEdits = await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false);
return tokenEdits.Where(t => t.Span.Start >= token.FullSpan.Start).ToImmutableArray();
}
// if formatting range fails, do format token one at least
var changes = await FormatRangeAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false);
if (changes.Length > 0)
{
return changes;
}
return (await FormatTokenAsync(document, options, token, formattingRules, cancellationToken).ConfigureAwait(false)).ToImmutableArray();
}
private static bool OnlySmartIndentCloseBrace(DocumentOptionSet options)
{
// User does not want auto-formatting (either in general, or for close braces in
// specific). So we only smart indent close braces when typed.
return !options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace) ||
!options.GetOption(FormattingOptions2.AutoFormattingOnTyping);
}
private static bool OnlySmartIndentOpenBrace(DocumentOptionSet options)
{
// User does not want auto-formatting . So we only smart indent open braces when typed.
// Note: there is no specific option for controlling formatting on open brace. So we
// don't have the symmetry with OnlySmartIndentCloseBrace.
return !options.GetOption(FormattingOptions2.AutoFormattingOnTyping);
}
private static async Task<SyntaxToken> GetTokenBeforeTheCaretAsync(Document document, int caretPosition, CancellationToken cancellationToken)
{
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var position = Math.Max(0, caretPosition - 1);
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(position, findInsideTrivia: true);
return token;
}
private static async Task<IList<TextChange>> FormatTokenAsync(Document document, OptionSet options, SyntaxToken token, IEnumerable<AbstractFormattingRule> formattingRules, CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formatter = CreateSmartTokenFormatter(options, formattingRules, root);
var changes = await formatter.FormatTokenAsync(document.Project.Solution.Workspace, token, cancellationToken).ConfigureAwait(false);
return changes;
}
private static ISmartTokenFormatter CreateSmartTokenFormatter(OptionSet optionSet, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxNode root)
=> new CSharpSmartTokenFormatter(optionSet, formattingRules, (CompilationUnitSyntax)root);
private static async Task<ImmutableArray<TextChange>> FormatRangeAsync(
Document document,
OptionSet options,
SyntaxToken endToken,
IEnumerable<AbstractFormattingRule> formattingRules,
CancellationToken cancellationToken)
{
if (!IsEndToken(endToken))
{
return ImmutableArray<TextChange>.Empty;
}
var tokenRange = FormattingRangeHelper.FindAppropriateRange(endToken);
if (tokenRange == null || tokenRange.Value.Item1.Equals(tokenRange.Value.Item2))
{
return ImmutableArray<TextChange>.Empty;
}
if (IsInvalidTokenKind(tokenRange.Value.Item1) || IsInvalidTokenKind(tokenRange.Value.Item2))
{
return ImmutableArray<TextChange>.Empty;
}
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var formatter = new CSharpSmartTokenFormatter(options, formattingRules, (CompilationUnitSyntax)root);
var changes = formatter.FormatRange(document.Project.Solution.Workspace, tokenRange.Value.Item1, tokenRange.Value.Item2, cancellationToken);
return changes.ToImmutableArray();
}
private static IEnumerable<AbstractFormattingRule> GetTypingRules(SyntaxToken tokenBeforeCaret)
{
// Typing introduces several challenges around formatting.
// Historically we've shipped several triggers that cause formatting to happen directly while typing.
// These include formatting of blocks when '}' is typed, formatting of statements when a ';' is typed, formatting of ```case```s when ':' typed, and many other cases.
// However, formatting during typing can potentially cause problems. This is because the surrounding code may not be complete,
// or may otherwise have syntax errors, and thus edits could have unintended consequences.
//
// Because of this, we introduce an extra rule into the set of formatting rules whose purpose is to actually make formatting *more*
// conservative and *less* willing willing to make edits to the tree.
// The primary effect this rule has is to assume that more code is on a single line (and thus should stay that way)
// despite what the tree actually looks like.
//
// It's ok that this is only during formatting that is caused by an edit because that formatting happens
// implicitly and thus has to be more careful, whereas an explicit format-document call only happens on-demand
// and can be more aggressive about what it's doing.
//
//
// For example, say you have the following code.
//
// ```c#
// class C
// {
// int P { get { return
// }
// ```
//
// Hitting ';' after 'return' should ideally only affect the 'return statement' and change it to:
//
// ```c#
// class C
// {
// int P { get { return;
// }
// ```
//
// During a normal format-document call, this is not what would happen.
// Specifically, because the parser will consume the '}' into the accessor,
// it will think the accessor spans multiple lines, and thus should not stay on a single line. This will produce:
//
// ```c#
// class C
// {
// int P
// {
// get
// {
// return;
// }
// ```
//
// Because it's ok for this to format in that fashion if format-document is invoked,
// but should not happen during typing, we insert a specialized rule *only* during typing to try to control this.
// During normal formatting we add 'keep on single line' suppression rules for blocks we find that are on a single line.
// But that won't work since this span is not on a single line:
//
// ```c#
// class C
// {
// int P { get [|{ return;
// }|]
// ```
//
// So, during typing, if we see any parent block is incomplete, we'll assume that
// all our parent blocks are incomplete and we will place the suppression span like so:
//
// ```c#
// class C
// {
// int P { get [|{ return;|]
// }
// ```
//
// This will have the desired effect of keeping these tokens on the same line, but only during typing scenarios.
if (tokenBeforeCaret.Kind() == SyntaxKind.CloseBraceToken ||
tokenBeforeCaret.Kind() == SyntaxKind.EndOfFileToken)
{
return SpecializedCollections.EmptyEnumerable<AbstractFormattingRule>();
}
return SpecializedCollections.SingletonEnumerable(TypingFormattingRule.Instance);
}
private static bool IsEndToken(SyntaxToken endToken)
{
if (endToken.IsKind(SyntaxKind.OpenBraceToken))
{
return false;
}
return true;
}
// We'll autoformat on n, t, e, only if they are the last character of the below
// keywords.
private static bool ValidSingleOrMultiCharactersTokenKind(char typedChar, SyntaxKind kind)
=> typedChar switch
{
'n' => kind == SyntaxKind.RegionKeyword || kind == SyntaxKind.EndRegionKeyword,
't' => kind == SyntaxKind.SelectKeyword,
'e' => kind == SyntaxKind.WhereKeyword,
_ => true,
};
private static bool IsInvalidTokenKind(SyntaxToken token)
{
// invalid token to be formatted
return token.IsKind(SyntaxKind.None) ||
token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
token.IsKind(SyntaxKind.EndOfFileToken);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/Core/Portable/Workspace/Solution/Checksum_Factory.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.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Serialization;
using Roslyn.Utilities;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis
{
// various factory methods. all these are just helper methods
internal partial class Checksum
{
private static readonly ObjectPool<IncrementalHash> s_incrementalHashPool =
new(() => IncrementalHash.CreateHash(HashAlgorithmName.SHA256), size: 20);
public static Checksum Create(IEnumerable<string> values)
{
using var pooledHash = s_incrementalHashPool.GetPooledObject();
using var pooledBuffer = SharedPools.ByteArray.GetPooledObject();
var hash = pooledHash.Object;
foreach (var value in values)
{
AppendData(hash, pooledBuffer.Object, value);
AppendData(hash, pooledBuffer.Object, "\0");
}
return From(hash.GetHashAndReset());
}
public static Checksum Create(string value)
{
using var pooledHash = s_incrementalHashPool.GetPooledObject();
using var pooledBuffer = SharedPools.ByteArray.GetPooledObject();
var hash = pooledHash.Object;
AppendData(hash, pooledBuffer.Object, value);
return From(hash.GetHashAndReset());
}
public static Checksum Create(Stream stream)
{
using var pooledHash = s_incrementalHashPool.GetPooledObject();
using var pooledBuffer = SharedPools.ByteArray.GetPooledObject();
var hash = pooledHash.Object;
var buffer = pooledBuffer.Object;
var bufferLength = buffer.Length;
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, bufferLength);
if (bytesRead > 0)
{
hash.AppendData(buffer, 0, bytesRead);
}
}
while (bytesRead > 0);
var bytes = hash.GetHashAndReset();
// if bytes array is bigger than certain size, checksum
// will truncate it to predetermined size. for more detail,
// see the Checksum type
//
// the truncation can happen since different hash algorithm or
// same algorithm on different platform can have different hash size
// which might be bigger than the Checksum HashSize.
//
// hash algorithm used here should remain functionally correct even
// after the truncation
return From(bytes);
}
public static Checksum Create(IObjectWritable @object)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
@object.WriteTo(objectWriter);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create(Checksum checksum1, Checksum checksum2)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var writer = new ObjectWriter(stream, leaveOpen: true))
{
checksum1.WriteTo(writer);
checksum2.WriteTo(writer);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create(Checksum checksum1, Checksum checksum2, Checksum checksum3)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var writer = new ObjectWriter(stream, leaveOpen: true))
{
checksum1.WriteTo(writer);
checksum2.WriteTo(writer);
checksum3.WriteTo(writer);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create(IEnumerable<Checksum> checksums)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var writer = new ObjectWriter(stream, leaveOpen: true))
{
foreach (var checksum in checksums)
checksum.WriteTo(writer);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create(ImmutableArray<byte> bytes)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var writer = new ObjectWriter(stream, leaveOpen: true))
{
for (var i = 0; i < bytes.Length; i++)
writer.WriteByte(bytes[i]);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create<T>(T value, ISerializerService serializer)
{
using var stream = SerializableBytes.CreateWritableStream();
using var context = SolutionReplicationContext.Create();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
serializer.Serialize(value!, objectWriter, context, CancellationToken.None);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create(ParseOptions value, ISerializerService serializer)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
serializer.SerializeParseOptions(value, objectWriter);
}
stream.Position = 0;
return Create(stream);
}
private static void AppendData(IncrementalHash hash, byte[] buffer, string value)
{
var stringBytes = MemoryMarshal.AsBytes(value.AsSpan());
Debug.Assert(stringBytes.Length == value.Length * 2);
var index = 0;
while (index < stringBytes.Length)
{
var remaining = stringBytes.Length - index;
var toCopy = Math.Min(remaining, buffer.Length);
stringBytes.Slice(index, toCopy).CopyTo(buffer);
hash.AppendData(buffer, 0, toCopy);
index += toCopy;
}
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Serialization;
using Roslyn.Utilities;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis
{
// various factory methods. all these are just helper methods
internal partial class Checksum
{
private static readonly ObjectPool<IncrementalHash> s_incrementalHashPool =
new(() => IncrementalHash.CreateHash(HashAlgorithmName.SHA256), size: 20);
public static Checksum Create(IEnumerable<string> values)
{
using var pooledHash = s_incrementalHashPool.GetPooledObject();
using var pooledBuffer = SharedPools.ByteArray.GetPooledObject();
var hash = pooledHash.Object;
foreach (var value in values)
{
AppendData(hash, pooledBuffer.Object, value);
AppendData(hash, pooledBuffer.Object, "\0");
}
return From(hash.GetHashAndReset());
}
public static Checksum Create(string value)
{
using var pooledHash = s_incrementalHashPool.GetPooledObject();
using var pooledBuffer = SharedPools.ByteArray.GetPooledObject();
var hash = pooledHash.Object;
AppendData(hash, pooledBuffer.Object, value);
return From(hash.GetHashAndReset());
}
public static Checksum Create(Stream stream)
{
using var pooledHash = s_incrementalHashPool.GetPooledObject();
using var pooledBuffer = SharedPools.ByteArray.GetPooledObject();
var hash = pooledHash.Object;
var buffer = pooledBuffer.Object;
var bufferLength = buffer.Length;
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, bufferLength);
if (bytesRead > 0)
{
hash.AppendData(buffer, 0, bytesRead);
}
}
while (bytesRead > 0);
var bytes = hash.GetHashAndReset();
// if bytes array is bigger than certain size, checksum
// will truncate it to predetermined size. for more detail,
// see the Checksum type
//
// the truncation can happen since different hash algorithm or
// same algorithm on different platform can have different hash size
// which might be bigger than the Checksum HashSize.
//
// hash algorithm used here should remain functionally correct even
// after the truncation
return From(bytes);
}
public static Checksum Create(IObjectWritable @object)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
@object.WriteTo(objectWriter);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create(Checksum checksum1, Checksum checksum2)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var writer = new ObjectWriter(stream, leaveOpen: true))
{
checksum1.WriteTo(writer);
checksum2.WriteTo(writer);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create(Checksum checksum1, Checksum checksum2, Checksum checksum3)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var writer = new ObjectWriter(stream, leaveOpen: true))
{
checksum1.WriteTo(writer);
checksum2.WriteTo(writer);
checksum3.WriteTo(writer);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create(IEnumerable<Checksum> checksums)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var writer = new ObjectWriter(stream, leaveOpen: true))
{
foreach (var checksum in checksums)
checksum.WriteTo(writer);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create(ImmutableArray<byte> bytes)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var writer = new ObjectWriter(stream, leaveOpen: true))
{
for (var i = 0; i < bytes.Length; i++)
writer.WriteByte(bytes[i]);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create<T>(T value, ISerializerService serializer)
{
using var stream = SerializableBytes.CreateWritableStream();
using var context = SolutionReplicationContext.Create();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
serializer.Serialize(value!, objectWriter, context, CancellationToken.None);
}
stream.Position = 0;
return Create(stream);
}
public static Checksum Create(ParseOptions value, ISerializerService serializer)
{
using var stream = SerializableBytes.CreateWritableStream();
using (var objectWriter = new ObjectWriter(stream, leaveOpen: true))
{
serializer.SerializeParseOptions(value, objectWriter);
}
stream.Position = 0;
return Create(stream);
}
private static void AppendData(IncrementalHash hash, byte[] buffer, string value)
{
var stringBytes = MemoryMarshal.AsBytes(value.AsSpan());
Debug.Assert(stringBytes.Length == value.Length * 2);
var index = 0;
while (index < stringBytes.Length)
{
var remaining = stringBytes.Length - index;
var toCopy = Math.Min(remaining, buffer.Length);
stringBytes.Slice(index, toCopy).CopyTo(buffer);
hash.AppendData(buffer, 0, toCopy);
index += toCopy;
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.State.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.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.AddConstructorParametersFromMembers
{
internal partial class AddConstructorParametersFromMembersCodeRefactoringProvider
{
private class State
{
public ImmutableArray<ConstructorCandidate> ConstructorCandidates { get; private set; }
[NotNull]
public INamedTypeSymbol? ContainingType { get; private set; }
public static async Task<State?> GenerateAsync(
ImmutableArray<ISymbol> selectedMembers,
Document document,
CancellationToken cancellationToken)
{
var state = new State();
if (!await state.TryInitializeAsync(
selectedMembers, document, cancellationToken).ConfigureAwait(false))
{
return null;
}
return state;
}
private async Task<bool> TryInitializeAsync(
ImmutableArray<ISymbol> selectedMembers,
Document document,
CancellationToken cancellationToken)
{
ContainingType = selectedMembers[0].ContainingType;
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
var parametersForSelectedMembers = DetermineParameters(selectedMembers, rules);
if (!selectedMembers.All(IsWritableInstanceFieldOrProperty) ||
ContainingType == null ||
ContainingType.TypeKind == TypeKind.Interface ||
parametersForSelectedMembers.IsEmpty)
{
return false;
}
ConstructorCandidates = await GetConstructorCandidatesInfoAsync(
ContainingType, selectedMembers, document, parametersForSelectedMembers, cancellationToken).ConfigureAwait(false);
return !ConstructorCandidates.IsEmpty;
}
/// <summary>
/// Try to find all constructors in <paramref name="containingType"/> whose parameters
/// are a subset of the selected members by comparing name.
/// These constructors will not be considered as potential candidates:
/// - if the constructor's parameter list contains 'ref' or 'params'
/// - any constructor that has a params[] parameter
/// - deserialization constructor
/// - implicit default constructor
/// </summary>
private static async Task<ImmutableArray<ConstructorCandidate>> GetConstructorCandidatesInfoAsync(
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> selectedMembers,
Document document,
ImmutableArray<IParameterSymbol> parametersForSelectedMembers,
CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<ConstructorCandidate>.GetInstance(out var applicableConstructors);
foreach (var constructor in containingType.InstanceConstructors)
{
if (await IsApplicableConstructorAsync(
constructor, document, parametersForSelectedMembers.SelectAsArray(p => p.Name), cancellationToken).ConfigureAwait(false))
{
applicableConstructors.Add(CreateConstructorCandidate(parametersForSelectedMembers, selectedMembers, constructor));
}
}
return applicableConstructors.ToImmutable();
}
private static async Task<bool> IsApplicableConstructorAsync(IMethodSymbol constructor, Document document, ImmutableArray<string> parameterNamesForSelectedMembers, CancellationToken cancellationToken)
{
var constructorParams = constructor.Parameters;
if (constructorParams.Length == 2)
{
var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var deserializationConstructorCheck = new DeserializationConstructorCheck(compilation);
if (deserializationConstructorCheck.IsDeserializationConstructor(constructor))
{
return false;
}
}
return constructorParams.All(parameter => parameter.RefKind == RefKind.None) &&
!constructor.IsImplicitlyDeclared &&
!constructorParams.Any(p => p.IsParams) &&
!SelectedMembersAlreadyExistAsParameters(parameterNamesForSelectedMembers, constructorParams);
}
private static bool SelectedMembersAlreadyExistAsParameters(ImmutableArray<string> parameterNamesForSelectedMembers, ImmutableArray<IParameterSymbol> constructorParams)
=> constructorParams.Length != 0 &&
!parameterNamesForSelectedMembers.Except(constructorParams.Select(p => p.Name)).Any();
private static ConstructorCandidate CreateConstructorCandidate(ImmutableArray<IParameterSymbol> parametersForSelectedMembers, ImmutableArray<ISymbol> selectedMembers, IMethodSymbol constructor)
{
using var _0 = ArrayBuilder<IParameterSymbol>.GetInstance(out var missingParametersBuilder);
using var _1 = ArrayBuilder<ISymbol>.GetInstance(out var missingMembersBuilder);
var constructorParamNames = constructor.Parameters.SelectAsArray(p => p.Name);
var zippedParametersAndSelectedMembers =
parametersForSelectedMembers.Zip(selectedMembers, (parameter, selectedMember) => (parameter, selectedMember));
foreach (var (parameter, selectedMember) in zippedParametersAndSelectedMembers)
{
if (!constructorParamNames.Contains(parameter.Name))
{
missingParametersBuilder.Add(parameter);
missingMembersBuilder.Add(selectedMember);
}
}
return new ConstructorCandidate(
constructor, missingMembersBuilder.ToImmutable(), missingParametersBuilder.ToImmutable());
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.AddConstructorParametersFromMembers
{
internal partial class AddConstructorParametersFromMembersCodeRefactoringProvider
{
private class State
{
public ImmutableArray<ConstructorCandidate> ConstructorCandidates { get; private set; }
[NotNull]
public INamedTypeSymbol? ContainingType { get; private set; }
public static async Task<State?> GenerateAsync(
ImmutableArray<ISymbol> selectedMembers,
Document document,
CancellationToken cancellationToken)
{
var state = new State();
if (!await state.TryInitializeAsync(
selectedMembers, document, cancellationToken).ConfigureAwait(false))
{
return null;
}
return state;
}
private async Task<bool> TryInitializeAsync(
ImmutableArray<ISymbol> selectedMembers,
Document document,
CancellationToken cancellationToken)
{
ContainingType = selectedMembers[0].ContainingType;
var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false);
var parametersForSelectedMembers = DetermineParameters(selectedMembers, rules);
if (!selectedMembers.All(IsWritableInstanceFieldOrProperty) ||
ContainingType == null ||
ContainingType.TypeKind == TypeKind.Interface ||
parametersForSelectedMembers.IsEmpty)
{
return false;
}
ConstructorCandidates = await GetConstructorCandidatesInfoAsync(
ContainingType, selectedMembers, document, parametersForSelectedMembers, cancellationToken).ConfigureAwait(false);
return !ConstructorCandidates.IsEmpty;
}
/// <summary>
/// Try to find all constructors in <paramref name="containingType"/> whose parameters
/// are a subset of the selected members by comparing name.
/// These constructors will not be considered as potential candidates:
/// - if the constructor's parameter list contains 'ref' or 'params'
/// - any constructor that has a params[] parameter
/// - deserialization constructor
/// - implicit default constructor
/// </summary>
private static async Task<ImmutableArray<ConstructorCandidate>> GetConstructorCandidatesInfoAsync(
INamedTypeSymbol containingType,
ImmutableArray<ISymbol> selectedMembers,
Document document,
ImmutableArray<IParameterSymbol> parametersForSelectedMembers,
CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<ConstructorCandidate>.GetInstance(out var applicableConstructors);
foreach (var constructor in containingType.InstanceConstructors)
{
if (await IsApplicableConstructorAsync(
constructor, document, parametersForSelectedMembers.SelectAsArray(p => p.Name), cancellationToken).ConfigureAwait(false))
{
applicableConstructors.Add(CreateConstructorCandidate(parametersForSelectedMembers, selectedMembers, constructor));
}
}
return applicableConstructors.ToImmutable();
}
private static async Task<bool> IsApplicableConstructorAsync(IMethodSymbol constructor, Document document, ImmutableArray<string> parameterNamesForSelectedMembers, CancellationToken cancellationToken)
{
var constructorParams = constructor.Parameters;
if (constructorParams.Length == 2)
{
var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var deserializationConstructorCheck = new DeserializationConstructorCheck(compilation);
if (deserializationConstructorCheck.IsDeserializationConstructor(constructor))
{
return false;
}
}
return constructorParams.All(parameter => parameter.RefKind == RefKind.None) &&
!constructor.IsImplicitlyDeclared &&
!constructorParams.Any(p => p.IsParams) &&
!SelectedMembersAlreadyExistAsParameters(parameterNamesForSelectedMembers, constructorParams);
}
private static bool SelectedMembersAlreadyExistAsParameters(ImmutableArray<string> parameterNamesForSelectedMembers, ImmutableArray<IParameterSymbol> constructorParams)
=> constructorParams.Length != 0 &&
!parameterNamesForSelectedMembers.Except(constructorParams.Select(p => p.Name)).Any();
private static ConstructorCandidate CreateConstructorCandidate(ImmutableArray<IParameterSymbol> parametersForSelectedMembers, ImmutableArray<ISymbol> selectedMembers, IMethodSymbol constructor)
{
using var _0 = ArrayBuilder<IParameterSymbol>.GetInstance(out var missingParametersBuilder);
using var _1 = ArrayBuilder<ISymbol>.GetInstance(out var missingMembersBuilder);
var constructorParamNames = constructor.Parameters.SelectAsArray(p => p.Name);
var zippedParametersAndSelectedMembers =
parametersForSelectedMembers.Zip(selectedMembers, (parameter, selectedMember) => (parameter, selectedMember));
foreach (var (parameter, selectedMember) in zippedParametersAndSelectedMembers)
{
if (!constructorParamNames.Contains(parameter.Name))
{
missingParametersBuilder.Add(parameter);
missingMembersBuilder.Add(selectedMember);
}
}
return new ConstructorCandidate(
constructor, missingMembersBuilder.ToImmutable(), missingParametersBuilder.ToImmutable());
}
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/BoolKeywordRecommender.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 BoolKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public BoolKeywordRecommender()
: base(SyntaxKind.BoolKeyword)
{
}
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.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_Boolean;
}
}
| // Licensed to the .NET Foundation under one or more 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 BoolKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public BoolKeywordRecommender()
: base(SyntaxKind.BoolKeyword)
{
}
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.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_Boolean;
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./eng/common/init-tools-native.ps1 | <#
.SYNOPSIS
Entry point script for installing native tools
.DESCRIPTION
Reads $RepoRoot\global.json file to determine native assets to install
and executes installers for those tools
.PARAMETER BaseUri
Base file directory or Url from which to acquire tool archives
.PARAMETER InstallDirectory
Directory to install native toolset. This is a command-line override for the default
Install directory precedence order:
- InstallDirectory command-line override
- NETCOREENG_INSTALL_DIRECTORY environment variable
- (default) %USERPROFILE%/.netcoreeng/native
.PARAMETER Clean
Switch specifying to not install anything, but cleanup native asset folders
.PARAMETER Force
Clean and then install tools
.PARAMETER DownloadRetries
Total number of retry attempts
.PARAMETER RetryWaitTimeInSeconds
Wait time between retry attempts in seconds
.PARAMETER GlobalJsonFile
File path to global.json file
.NOTES
#>
[CmdletBinding(PositionalBinding=$false)]
Param (
[string] $BaseUri = 'https://netcorenativeassets.blob.core.windows.net/resource-packages/external',
[string] $InstallDirectory,
[switch] $Clean = $False,
[switch] $Force = $False,
[int] $DownloadRetries = 5,
[int] $RetryWaitTimeInSeconds = 30,
[string] $GlobalJsonFile
)
if (!$GlobalJsonFile) {
$GlobalJsonFile = Join-Path (Get-Item $PSScriptRoot).Parent.Parent.FullName 'global.json'
}
Set-StrictMode -version 2.0
$ErrorActionPreference='Stop'
. $PSScriptRoot\pipeline-logging-functions.ps1
Import-Module -Name (Join-Path $PSScriptRoot 'native\CommonLibrary.psm1')
try {
# Define verbose switch if undefined
$Verbose = $VerbosePreference -Eq 'Continue'
$EngCommonBaseDir = Join-Path $PSScriptRoot 'native\'
$NativeBaseDir = $InstallDirectory
if (!$NativeBaseDir) {
$NativeBaseDir = CommonLibrary\Get-NativeInstallDirectory
}
$Env:CommonLibrary_NativeInstallDir = $NativeBaseDir
$InstallBin = Join-Path $NativeBaseDir 'bin'
$InstallerPath = Join-Path $EngCommonBaseDir 'install-tool.ps1'
# Process tools list
Write-Host "Processing $GlobalJsonFile"
If (-Not (Test-Path $GlobalJsonFile)) {
Write-Host "Unable to find '$GlobalJsonFile'"
exit 0
}
$NativeTools = Get-Content($GlobalJsonFile) -Raw |
ConvertFrom-Json |
Select-Object -Expand 'native-tools' -ErrorAction SilentlyContinue
if ($NativeTools) {
$NativeTools.PSObject.Properties | ForEach-Object {
$ToolName = $_.Name
$ToolVersion = $_.Value
$LocalInstallerArguments = @{ ToolName = "$ToolName" }
$LocalInstallerArguments += @{ InstallPath = "$InstallBin" }
$LocalInstallerArguments += @{ BaseUri = "$BaseUri" }
$LocalInstallerArguments += @{ CommonLibraryDirectory = "$EngCommonBaseDir" }
$LocalInstallerArguments += @{ Version = "$ToolVersion" }
if ($Verbose) {
$LocalInstallerArguments += @{ Verbose = $True }
}
if (Get-Variable 'Force' -ErrorAction 'SilentlyContinue') {
if($Force) {
$LocalInstallerArguments += @{ Force = $True }
}
}
if ($Clean) {
$LocalInstallerArguments += @{ Clean = $True }
}
Write-Verbose "Installing $ToolName version $ToolVersion"
Write-Verbose "Executing '$InstallerPath $($LocalInstallerArguments.Keys.ForEach({"-$_ '$($LocalInstallerArguments.$_)'"}) -join ' ')'"
& $InstallerPath @LocalInstallerArguments
if ($LASTEXITCODE -Ne "0") {
$errMsg = "$ToolName installation failed"
if ((Get-Variable 'DoNotAbortNativeToolsInstallationOnFailure' -ErrorAction 'SilentlyContinue') -and $DoNotAbortNativeToolsInstallationOnFailure) {
$showNativeToolsWarning = $true
if ((Get-Variable 'DoNotDisplayNativeToolsInstallationWarnings' -ErrorAction 'SilentlyContinue') -and $DoNotDisplayNativeToolsInstallationWarnings) {
$showNativeToolsWarning = $false
}
if ($showNativeToolsWarning) {
Write-Warning $errMsg
}
$toolInstallationFailure = $true
} else {
# We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482
Write-Host $errMsg
exit 1
}
}
}
if ((Get-Variable 'toolInstallationFailure' -ErrorAction 'SilentlyContinue') -and $toolInstallationFailure) {
# We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482
Write-Host 'Native tools bootstrap failed'
exit 1
}
}
else {
Write-Host 'No native tools defined in global.json'
exit 0
}
if ($Clean) {
exit 0
}
if (Test-Path $InstallBin) {
Write-Host 'Native tools are available from ' (Convert-Path -Path $InstallBin)
Write-Host "##vso[task.prependpath]$(Convert-Path -Path $InstallBin)"
return $InstallBin
}
else {
Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message 'Native tools install directory does not exist, installation failed'
exit 1
}
exit 0
}
catch {
Write-Host $_.ScriptStackTrace
Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message $_
ExitWithExitCode 1
}
| <#
.SYNOPSIS
Entry point script for installing native tools
.DESCRIPTION
Reads $RepoRoot\global.json file to determine native assets to install
and executes installers for those tools
.PARAMETER BaseUri
Base file directory or Url from which to acquire tool archives
.PARAMETER InstallDirectory
Directory to install native toolset. This is a command-line override for the default
Install directory precedence order:
- InstallDirectory command-line override
- NETCOREENG_INSTALL_DIRECTORY environment variable
- (default) %USERPROFILE%/.netcoreeng/native
.PARAMETER Clean
Switch specifying to not install anything, but cleanup native asset folders
.PARAMETER Force
Clean and then install tools
.PARAMETER DownloadRetries
Total number of retry attempts
.PARAMETER RetryWaitTimeInSeconds
Wait time between retry attempts in seconds
.PARAMETER GlobalJsonFile
File path to global.json file
.NOTES
#>
[CmdletBinding(PositionalBinding=$false)]
Param (
[string] $BaseUri = 'https://netcorenativeassets.blob.core.windows.net/resource-packages/external',
[string] $InstallDirectory,
[switch] $Clean = $False,
[switch] $Force = $False,
[int] $DownloadRetries = 5,
[int] $RetryWaitTimeInSeconds = 30,
[string] $GlobalJsonFile
)
if (!$GlobalJsonFile) {
$GlobalJsonFile = Join-Path (Get-Item $PSScriptRoot).Parent.Parent.FullName 'global.json'
}
Set-StrictMode -version 2.0
$ErrorActionPreference='Stop'
. $PSScriptRoot\pipeline-logging-functions.ps1
Import-Module -Name (Join-Path $PSScriptRoot 'native\CommonLibrary.psm1')
try {
# Define verbose switch if undefined
$Verbose = $VerbosePreference -Eq 'Continue'
$EngCommonBaseDir = Join-Path $PSScriptRoot 'native\'
$NativeBaseDir = $InstallDirectory
if (!$NativeBaseDir) {
$NativeBaseDir = CommonLibrary\Get-NativeInstallDirectory
}
$Env:CommonLibrary_NativeInstallDir = $NativeBaseDir
$InstallBin = Join-Path $NativeBaseDir 'bin'
$InstallerPath = Join-Path $EngCommonBaseDir 'install-tool.ps1'
# Process tools list
Write-Host "Processing $GlobalJsonFile"
If (-Not (Test-Path $GlobalJsonFile)) {
Write-Host "Unable to find '$GlobalJsonFile'"
exit 0
}
$NativeTools = Get-Content($GlobalJsonFile) -Raw |
ConvertFrom-Json |
Select-Object -Expand 'native-tools' -ErrorAction SilentlyContinue
if ($NativeTools) {
$NativeTools.PSObject.Properties | ForEach-Object {
$ToolName = $_.Name
$ToolVersion = $_.Value
$LocalInstallerArguments = @{ ToolName = "$ToolName" }
$LocalInstallerArguments += @{ InstallPath = "$InstallBin" }
$LocalInstallerArguments += @{ BaseUri = "$BaseUri" }
$LocalInstallerArguments += @{ CommonLibraryDirectory = "$EngCommonBaseDir" }
$LocalInstallerArguments += @{ Version = "$ToolVersion" }
if ($Verbose) {
$LocalInstallerArguments += @{ Verbose = $True }
}
if (Get-Variable 'Force' -ErrorAction 'SilentlyContinue') {
if($Force) {
$LocalInstallerArguments += @{ Force = $True }
}
}
if ($Clean) {
$LocalInstallerArguments += @{ Clean = $True }
}
Write-Verbose "Installing $ToolName version $ToolVersion"
Write-Verbose "Executing '$InstallerPath $($LocalInstallerArguments.Keys.ForEach({"-$_ '$($LocalInstallerArguments.$_)'"}) -join ' ')'"
& $InstallerPath @LocalInstallerArguments
if ($LASTEXITCODE -Ne "0") {
$errMsg = "$ToolName installation failed"
if ((Get-Variable 'DoNotAbortNativeToolsInstallationOnFailure' -ErrorAction 'SilentlyContinue') -and $DoNotAbortNativeToolsInstallationOnFailure) {
$showNativeToolsWarning = $true
if ((Get-Variable 'DoNotDisplayNativeToolsInstallationWarnings' -ErrorAction 'SilentlyContinue') -and $DoNotDisplayNativeToolsInstallationWarnings) {
$showNativeToolsWarning = $false
}
if ($showNativeToolsWarning) {
Write-Warning $errMsg
}
$toolInstallationFailure = $true
} else {
# We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482
Write-Host $errMsg
exit 1
}
}
}
if ((Get-Variable 'toolInstallationFailure' -ErrorAction 'SilentlyContinue') -and $toolInstallationFailure) {
# We cannot change this to Write-PipelineTelemetryError because of https://github.com/dotnet/arcade/issues/4482
Write-Host 'Native tools bootstrap failed'
exit 1
}
}
else {
Write-Host 'No native tools defined in global.json'
exit 0
}
if ($Clean) {
exit 0
}
if (Test-Path $InstallBin) {
Write-Host 'Native tools are available from ' (Convert-Path -Path $InstallBin)
Write-Host "##vso[task.prependpath]$(Convert-Path -Path $InstallBin)"
return $InstallBin
}
else {
Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message 'Native tools install directory does not exist, installation failed'
exit 1
}
exit 0
}
catch {
Write-Host $_.ScriptStackTrace
Write-PipelineTelemetryError -Category 'NativeToolsBootstrap' -Message $_
ExitWithExitCode 1
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/Embed.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>
<VBRuntime>Embed</VBRuntime>
</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>
</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>
<VBRuntime>Embed</VBRuntime>
</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>
</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 | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SemanticModelExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class SemanticModelExtensions
{
/// <summary>
/// Gets semantic information, such as type, symbols, and diagnostics, about the parent of a token.
/// </summary>
/// <param name="semanticModel">The SemanticModel object to get semantic information
/// from.</param>
/// <param name="token">The token to get semantic information from. This must be part of the
/// syntax tree associated with the binding.</param>
/// <param name="cancellationToken">A cancellation token.</param>
public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
=> semanticModel.GetSymbolInfo(token.Parent!, cancellationToken);
public static ISymbol GetRequiredDeclaredSymbol(this SemanticModel semanticModel, SyntaxNode declaration, CancellationToken cancellationToken)
{
return semanticModel.GetDeclaredSymbol(declaration, cancellationToken)
?? throw new InvalidOperationException();
}
public static ISymbol GetRequiredEnclosingSymbol(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingSymbol(position, cancellationToken)
?? throw new InvalidOperationException();
}
public static TSymbol? GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
where TSymbol : class, ISymbol
{
for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken);
symbol != null;
symbol = symbol.ContainingSymbol)
{
if (symbol is TSymbol tSymbol)
{
return tSymbol;
}
}
return null;
}
public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken) ??
(ISymbol)semanticModel.Compilation.Assembly;
}
public static INamedTypeSymbol? GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken);
public static INamespaceSymbol? GetEnclosingNamespace(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.GetEnclosingSymbol<INamespaceSymbol>(position, cancellationToken);
public static IEnumerable<ISymbol> GetExistingSymbols(
this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null)
{
// Ignore an anonymous type property or tuple field. It's ok if they have a name that
// matches the name of the local we're introducing.
return semanticModel.GetAllDeclaredSymbols(container, cancellationToken, descendInto)
.Where(s => !s.IsAnonymousTypeProperty() && !s.IsTupleField());
}
public static SemanticModel GetOriginalSemanticModel(this SemanticModel semanticModel)
{
if (!semanticModel.IsSpeculativeSemanticModel)
{
return semanticModel;
}
Contract.ThrowIfNull(semanticModel.ParentModel);
Contract.ThrowIfTrue(semanticModel.ParentModel.IsSpeculativeSemanticModel);
Contract.ThrowIfTrue(semanticModel.ParentModel.ParentModel != null);
return semanticModel.ParentModel;
}
public static HashSet<ISymbol> GetAllDeclaredSymbols(
this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? filter = null)
{
var symbols = new HashSet<ISymbol>();
if (container != null)
{
GetAllDeclaredSymbols(semanticModel, container, symbols, cancellationToken, filter);
}
return symbols;
}
private static void GetAllDeclaredSymbols(
SemanticModel semanticModel, SyntaxNode node,
HashSet<ISymbol> symbols, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null)
{
var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken);
if (symbol != null)
{
symbols.Add(symbol);
}
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
{
var childNode = child.AsNode()!;
if (ShouldDescendInto(childNode, descendInto))
{
GetAllDeclaredSymbols(semanticModel, childNode, symbols, cancellationToken, descendInto);
}
}
}
static bool ShouldDescendInto(SyntaxNode node, Func<SyntaxNode, bool>? filter)
=> filter != null ? filter(node) : 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.Generic;
using System.Linq;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class SemanticModelExtensions
{
/// <summary>
/// Gets semantic information, such as type, symbols, and diagnostics, about the parent of a token.
/// </summary>
/// <param name="semanticModel">The SemanticModel object to get semantic information
/// from.</param>
/// <param name="token">The token to get semantic information from. This must be part of the
/// syntax tree associated with the binding.</param>
/// <param name="cancellationToken">A cancellation token.</param>
public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
=> semanticModel.GetSymbolInfo(token.Parent!, cancellationToken);
public static ISymbol GetRequiredDeclaredSymbol(this SemanticModel semanticModel, SyntaxNode declaration, CancellationToken cancellationToken)
{
return semanticModel.GetDeclaredSymbol(declaration, cancellationToken)
?? throw new InvalidOperationException();
}
public static ISymbol GetRequiredEnclosingSymbol(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingSymbol(position, cancellationToken)
?? throw new InvalidOperationException();
}
public static TSymbol? GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
where TSymbol : class, ISymbol
{
for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken);
symbol != null;
symbol = symbol.ContainingSymbol)
{
if (symbol is TSymbol tSymbol)
{
return tSymbol;
}
}
return null;
}
public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken) ??
(ISymbol)semanticModel.Compilation.Assembly;
}
public static INamedTypeSymbol? GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken);
public static INamespaceSymbol? GetEnclosingNamespace(this SemanticModel semanticModel, int position, CancellationToken cancellationToken)
=> semanticModel.GetEnclosingSymbol<INamespaceSymbol>(position, cancellationToken);
public static IEnumerable<ISymbol> GetExistingSymbols(
this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null)
{
// Ignore an anonymous type property or tuple field. It's ok if they have a name that
// matches the name of the local we're introducing.
return semanticModel.GetAllDeclaredSymbols(container, cancellationToken, descendInto)
.Where(s => !s.IsAnonymousTypeProperty() && !s.IsTupleField());
}
public static SemanticModel GetOriginalSemanticModel(this SemanticModel semanticModel)
{
if (!semanticModel.IsSpeculativeSemanticModel)
{
return semanticModel;
}
Contract.ThrowIfNull(semanticModel.ParentModel);
Contract.ThrowIfTrue(semanticModel.ParentModel.IsSpeculativeSemanticModel);
Contract.ThrowIfTrue(semanticModel.ParentModel.ParentModel != null);
return semanticModel.ParentModel;
}
public static HashSet<ISymbol> GetAllDeclaredSymbols(
this SemanticModel semanticModel, SyntaxNode? container, CancellationToken cancellationToken, Func<SyntaxNode, bool>? filter = null)
{
var symbols = new HashSet<ISymbol>();
if (container != null)
{
GetAllDeclaredSymbols(semanticModel, container, symbols, cancellationToken, filter);
}
return symbols;
}
private static void GetAllDeclaredSymbols(
SemanticModel semanticModel, SyntaxNode node,
HashSet<ISymbol> symbols, CancellationToken cancellationToken, Func<SyntaxNode, bool>? descendInto = null)
{
var symbol = semanticModel.GetDeclaredSymbol(node, cancellationToken);
if (symbol != null)
{
symbols.Add(symbol);
}
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
{
var childNode = child.AsNode()!;
if (ShouldDescendInto(childNode, descendInto))
{
GetAllDeclaredSymbols(semanticModel, childNode, symbols, cancellationToken, descendInto);
}
}
}
static bool ShouldDescendInto(SyntaxNode node, Func<SyntaxNode, bool>? filter)
=> filter != null ? filter(node) : true;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/EditorFeatures/Core/Shared/Utilities/ForegroundThreadAffinitizedObject.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
/// <summary>
/// Base class that allows some helpers for detecting whether we're on the main WPF foreground thread, or
/// a background thread. It also allows scheduling work to the foreground thread at below input priority.
/// </summary>
internal class ForegroundThreadAffinitizedObject
{
private readonly IThreadingContext _threadingContext;
internal IThreadingContext ThreadingContext => _threadingContext;
public ForegroundThreadAffinitizedObject(IThreadingContext threadingContext, bool assertIsForeground = false)
{
_threadingContext = threadingContext ?? throw new ArgumentNullException(nameof(threadingContext));
// ForegroundThreadAffinitizedObject might not necessarily be created on a foreground thread.
// AssertIsForeground here only if the object must be created on a foreground thread.
if (assertIsForeground)
{
// Assert we have some kind of foreground thread
Contract.ThrowIfFalse(threadingContext.HasMainThread);
AssertIsForeground();
}
}
public bool IsForeground()
=> _threadingContext.JoinableTaskContext.IsOnMainThread;
public void AssertIsForeground()
{
var whenCreatedThread = _threadingContext.JoinableTaskContext.MainThread;
var currentThread = Thread.CurrentThread;
// In debug, provide a lot more information so that we can track down unit test flakiness.
// This is too expensive to do in retail as it creates way too many allocations.
Debug.Assert(currentThread == whenCreatedThread,
"When created thread id : " + whenCreatedThread?.ManagedThreadId + "\r\n" +
"When created thread name: " + whenCreatedThread?.Name + "\r\n" +
"Current thread id : " + currentThread?.ManagedThreadId + "\r\n" +
"Current thread name : " + currentThread?.Name);
// But, in retail, do the check as well, so that we can catch problems that happen in the wild.
Contract.ThrowIfFalse(_threadingContext.JoinableTaskContext.IsOnMainThread);
}
public void AssertIsBackground()
=> Contract.ThrowIfTrue(IsForeground());
/// <summary>
/// A helpful marker method that can be used by deriving classes to indicate that a
/// method can be called from any thread and is not foreground or background affinitized.
/// This is useful so that every method in deriving class can have some sort of marker
/// on each method stating the threading constraints (FG-only/BG-only/Any-thread).
/// </summary>
public static void ThisCanBeCalledOnAnyThread()
{
// Does nothing.
}
public Task InvokeBelowInputPriorityAsync(Action action, CancellationToken cancellationToken = default)
{
if (IsForeground() && !IsInputPending())
{
// Optimize to inline the action if we're already on the foreground thread
// and there's no pending user input.
action();
return Task.CompletedTask;
}
else
{
return Task.Factory.SafeStartNewFromAsync(
async () =>
{
await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
action();
},
cancellationToken,
TaskScheduler.Default);
}
}
/// <summary>
/// Returns true if any keyboard or mouse button input is pending on the message queue.
/// </summary>
protected static bool IsInputPending()
{
// The code below invokes into user32.dll, which is not available in non-Windows.
if (PlatformInformation.IsUnix)
{
return false;
}
// The return value of GetQueueStatus is HIWORD:LOWORD.
// A non-zero value in HIWORD indicates some input message in the queue.
var result = NativeMethods.GetQueueStatus(NativeMethods.QS_INPUT);
const uint InputMask = NativeMethods.QS_INPUT | (NativeMethods.QS_INPUT << 16);
return (result & InputMask) != 0;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
/// <summary>
/// Base class that allows some helpers for detecting whether we're on the main WPF foreground thread, or
/// a background thread. It also allows scheduling work to the foreground thread at below input priority.
/// </summary>
internal class ForegroundThreadAffinitizedObject
{
private readonly IThreadingContext _threadingContext;
internal IThreadingContext ThreadingContext => _threadingContext;
public ForegroundThreadAffinitizedObject(IThreadingContext threadingContext, bool assertIsForeground = false)
{
_threadingContext = threadingContext ?? throw new ArgumentNullException(nameof(threadingContext));
// ForegroundThreadAffinitizedObject might not necessarily be created on a foreground thread.
// AssertIsForeground here only if the object must be created on a foreground thread.
if (assertIsForeground)
{
// Assert we have some kind of foreground thread
Contract.ThrowIfFalse(threadingContext.HasMainThread);
AssertIsForeground();
}
}
public bool IsForeground()
=> _threadingContext.JoinableTaskContext.IsOnMainThread;
public void AssertIsForeground()
{
var whenCreatedThread = _threadingContext.JoinableTaskContext.MainThread;
var currentThread = Thread.CurrentThread;
// In debug, provide a lot more information so that we can track down unit test flakiness.
// This is too expensive to do in retail as it creates way too many allocations.
Debug.Assert(currentThread == whenCreatedThread,
"When created thread id : " + whenCreatedThread?.ManagedThreadId + "\r\n" +
"When created thread name: " + whenCreatedThread?.Name + "\r\n" +
"Current thread id : " + currentThread?.ManagedThreadId + "\r\n" +
"Current thread name : " + currentThread?.Name);
// But, in retail, do the check as well, so that we can catch problems that happen in the wild.
Contract.ThrowIfFalse(_threadingContext.JoinableTaskContext.IsOnMainThread);
}
public void AssertIsBackground()
=> Contract.ThrowIfTrue(IsForeground());
/// <summary>
/// A helpful marker method that can be used by deriving classes to indicate that a
/// method can be called from any thread and is not foreground or background affinitized.
/// This is useful so that every method in deriving class can have some sort of marker
/// on each method stating the threading constraints (FG-only/BG-only/Any-thread).
/// </summary>
public static void ThisCanBeCalledOnAnyThread()
{
// Does nothing.
}
public Task InvokeBelowInputPriorityAsync(Action action, CancellationToken cancellationToken = default)
{
if (IsForeground() && !IsInputPending())
{
// Optimize to inline the action if we're already on the foreground thread
// and there's no pending user input.
action();
return Task.CompletedTask;
}
else
{
return Task.Factory.SafeStartNewFromAsync(
async () =>
{
await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
action();
},
cancellationToken,
TaskScheduler.Default);
}
}
/// <summary>
/// Returns true if any keyboard or mouse button input is pending on the message queue.
/// </summary>
protected static bool IsInputPending()
{
// The code below invokes into user32.dll, which is not available in non-Windows.
if (PlatformInformation.IsUnix)
{
return false;
}
// The return value of GetQueueStatus is HIWORD:LOWORD.
// A non-zero value in HIWORD indicates some input message in the queue.
var result = NativeMethods.GetQueueStatus(NativeMethods.QS_INPUT);
const uint InputMask = NativeMethods.QS_INPUT | (NativeMethods.QS_INPUT << 16);
return (result & InputMask) != 0;
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Core/CodeAnalysisTest/Collections/TestExtensionsMethods.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.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/TestExtensionsMethods.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
internal static partial class TestExtensionsMethods
{
internal static void ValidateDefaultThisBehavior(Action a)
{
Assert.Throws<NullReferenceException>(a);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/TestExtensionsMethods.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
internal static partial class TestExtensionsMethods
{
internal static void ValidateDefaultThisBehavior(Action a)
{
Assert.Throws<NullReferenceException>(a);
}
}
}
| -1 |
dotnet/roslyn | 55,224 | EnC - Tests for lambda improvements | C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | davidwengier | 2021-07-29T11:36:37Z | 2021-08-30T20:11:14Z | 8de6661fc91b8c6c93d1c506ca573e8180bae139 | 3fdd28bc26238f717ec1124efc7e1f9c2158bce2 | EnC - Tests for lambda improvements. C# 10 Lambda improvements:
* Attributes: added editing and metadata tests
* Explicit return types: added editing test
* Natural type: N/A (and I used it in one of the tests just in case anyway)
/cc @cston in case I missed any improvements or important scenarios. | ./src/Compilers/Test/Resources/Core/SymbolsTests/CorLibrary/GuidTest2.exe | MZ @ !L!This program cannot be run in DOS mode.
$ PE L yL n# @ @ @ # O @ ` H .text t `.rsrc @ @ @.reloc ` @ B P# H p 0
o
&*(
* BSJB v4.0.30319 l #~ #Strings H #US P #GUID ` L #Blob G %3
0 ) b B B
) P 7
g < |