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,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Compilers/Server/VBCSCompilerTests/AnalyzerConsistencyCheckerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class AnalyzerConsistencyCheckerTests : TestBase { private ICompilerServerLogger Logger { get; } public AnalyzerConsistencyCheckerTests(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } [Fact] public void MissingReference() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var analyzerReferences = ImmutableArray.Create(new CommandLineAnalyzerReference("Alpha.dll")); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader(), Logger); Assert.True(result); } [Fact] public void AllChecksPassed() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var betaDll = directory.CreateFile("Beta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Beta); var gammaDll = directory.CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var deltaDll = directory.CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var analyzerReferences = ImmutableArray.Create( new CommandLineAnalyzerReference("Alpha.dll"), new CommandLineAnalyzerReference("Beta.dll"), new CommandLineAnalyzerReference("Gamma.dll"), new CommandLineAnalyzerReference("Delta.dll")); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader(), Logger); Assert.True(result); } [Fact] public void DifferingMvids() { var directory = Temp.CreateDirectory(); // Load Beta.dll from the future Alpha.dll path to prime the assembly loader var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Beta); var assemblyLoader = new InMemoryAssemblyLoader(); var betaAssembly = assemblyLoader.LoadFromPath(alphaDll.Path); alphaDll.WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var gammaDll = directory.CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var deltaDll = directory.CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var analyzerReferences = ImmutableArray.Create( new CommandLineAnalyzerReference("Alpha.dll"), new CommandLineAnalyzerReference("Gamma.dll"), new CommandLineAnalyzerReference("Delta.dll")); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, assemblyLoader, Logger); Assert.False(result); } [Fact] public void AssemblyLoadException() { var directory = Temp.CreateDirectory(); var deltaDll = directory.CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var analyzerReferences = ImmutableArray.Create( new CommandLineAnalyzerReference("Delta.dll")); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, TestAnalyzerAssemblyLoader.LoadNotImplemented, Logger); Assert.False(result); } [Fact] public void NetstandardIgnored() { var directory = Temp.CreateDirectory(); const string name = "netstandardRef"; var comp = CSharpCompilation.Create( name, new[] { SyntaxFactory.ParseSyntaxTree(@"class C {}") }, references: new MetadataReference[] { MetadataReference.CreateFromImage(TestMetadata.ResourcesNetStandard20.netstandard) }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: Diagnostic.MaxWarningLevel)); var compFile = directory.CreateFile(name); comp.Emit(compFile.Path); var analyzerReferences = ImmutableArray.Create(new CommandLineAnalyzerReference(name)); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader(), Logger); Assert.True(result); } private class InMemoryAssemblyLoader : IAnalyzerAssemblyLoader { private readonly Dictionary<string, Assembly> _assemblies = new Dictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase); public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { Assembly assembly; if (!_assemblies.TryGetValue(fullPath, out assembly)) { var bytes = File.ReadAllBytes(fullPath); assembly = Assembly.Load(bytes); _assemblies[fullPath] = assembly; } return assembly; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Microsoft.CodeAnalysis.CSharp; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class AnalyzerConsistencyCheckerTests : TestBase { private ICompilerServerLogger Logger { get; } public AnalyzerConsistencyCheckerTests(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } [Fact] public void MissingReference() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var analyzerReferences = ImmutableArray.Create(new CommandLineAnalyzerReference("Alpha.dll")); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader(), Logger); Assert.True(result); } [Fact] public void AllChecksPassed() { var directory = Temp.CreateDirectory(); var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var betaDll = directory.CreateFile("Beta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Beta); var gammaDll = directory.CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var deltaDll = directory.CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var analyzerReferences = ImmutableArray.Create( new CommandLineAnalyzerReference("Alpha.dll"), new CommandLineAnalyzerReference("Beta.dll"), new CommandLineAnalyzerReference("Gamma.dll"), new CommandLineAnalyzerReference("Delta.dll")); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader(), Logger); Assert.True(result); } [Fact] public void DifferingMvids() { var directory = Temp.CreateDirectory(); // Load Beta.dll from the future Alpha.dll path to prime the assembly loader var alphaDll = directory.CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Beta); var assemblyLoader = new InMemoryAssemblyLoader(); var betaAssembly = assemblyLoader.LoadFromPath(alphaDll.Path); alphaDll.WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var gammaDll = directory.CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var deltaDll = directory.CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var analyzerReferences = ImmutableArray.Create( new CommandLineAnalyzerReference("Alpha.dll"), new CommandLineAnalyzerReference("Gamma.dll"), new CommandLineAnalyzerReference("Delta.dll")); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, assemblyLoader, Logger); Assert.False(result); } [Fact] public void AssemblyLoadException() { var directory = Temp.CreateDirectory(); var deltaDll = directory.CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var analyzerReferences = ImmutableArray.Create( new CommandLineAnalyzerReference("Delta.dll")); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, TestAnalyzerAssemblyLoader.LoadNotImplemented, Logger); Assert.False(result); } [Fact] public void NetstandardIgnored() { var directory = Temp.CreateDirectory(); const string name = "netstandardRef"; var comp = CSharpCompilation.Create( name, new[] { SyntaxFactory.ParseSyntaxTree(@"class C {}") }, references: new MetadataReference[] { MetadataReference.CreateFromImage(TestMetadata.ResourcesNetStandard20.netstandard) }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: Diagnostic.MaxWarningLevel)); var compFile = directory.CreateFile(name); comp.Emit(compFile.Path); var analyzerReferences = ImmutableArray.Create(new CommandLineAnalyzerReference(name)); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, new InMemoryAssemblyLoader(), Logger); Assert.True(result); } private class InMemoryAssemblyLoader : IAnalyzerAssemblyLoader { private readonly Dictionary<string, Assembly> _assemblies = new Dictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase); public void AddDependencyLocation(string fullPath) { } public Assembly LoadFromPath(string fullPath) { Assembly assembly; if (!_assemblies.TryGetValue(fullPath, out assembly)) { var bytes = File.ReadAllBytes(fullPath); assembly = Assembly.Load(bytes); _assemblies[fullPath] = assembly; } return assembly; } } } }
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedParameterSymbol.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 Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Base (simplified) class for synthesized parameter symbols of methods that have been synthesized. E.g. the parameters of delegate methods ''' </summary> Friend Class SynthesizedParameterSimpleSymbol Inherits ParameterSymbol Protected ReadOnly _container As MethodSymbol Protected ReadOnly _type As TypeSymbol Protected ReadOnly _ordinal As Integer Protected ReadOnly _name As String ''' <summary> ''' Initializes a new instance of the <see cref="SynthesizedParameterSymbol" /> class. ''' </summary> ''' <param name="container">The containing symbol</param> ''' <param name="type">The type of this parameter</param> ''' <param name="ordinal">The ordinal number of this parameter</param> ''' <param name="name">The name of this parameter</param> Public Sub New(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, name As String) Me._container = container Me._type = type Me._ordinal = ordinal Me._name = name End Sub ''' <summary> ''' Gets the containing symbol. ''' </summary> Public NotOverridable Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me._container End Get End Property ''' <summary> ''' The list of custom modifiers, if any, associated with the parameter. Evaluate this property only if IsModified is true. ''' </summary> Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property ''' <summary> ''' A compile time constant value that should be supplied as the corresponding argument value by callers that do not explicitly specify an argument value for this parameter. ''' </summary> Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get Return Nothing End Get End Property ''' <summary> ''' True if the parameter has a default value that should be supplied as the argument value by a caller for which the argument value has not been explicitly specified. ''' </summary> Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is by ref. ''' </summary> ''' <value> ''' <c>true</c> if this instance is by ref; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsByRef As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsMetadataIn As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsMetadataOut As Boolean Get Return False End Get End Property Friend Shared Function IsMarshalAsAttributeApplicable(propertySetter As MethodSymbol) As Boolean Debug.Assert(propertySetter.MethodKind = MethodKind.PropertySet) Return propertySetter.ContainingType.IsInterface End Function Friend Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData Get ' Dev11 uses marshalling data of a return type of the containing method for the Value parameter ' of an interface property setter. Dim method = DirectCast(Me.ContainingSymbol, MethodSymbol) If method.MethodKind = MethodKind.PropertySet AndAlso IsMarshalAsAttributeApplicable(method) Then Return DirectCast(method.AssociatedSymbol, SourcePropertySymbol).ReturnTypeMarshallingInformation End If Return Nothing End Get End Property Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get Return IsByRef End Get End Property Friend Overrides ReadOnly Property HasOptionCompare As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property CallerArgumentExpressionParameterIndex As Integer Get Return -1 End Get End Property ''' <summary> ''' True if the argument value must be included in the marshalled arguments passed to a remote callee only if it is different from the default value (if there is one). ''' </summary> Public Overrides ReadOnly Property IsOptional As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is param array. ''' </summary> ''' <value> ''' <c>true</c> if this instance is param array; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsParamArray As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether the symbol was generated by the compiler ''' rather than declared explicitly. ''' </summary> Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property ''' <summary> ''' A potentially empty collection of locations that correspond to this instance. ''' </summary> Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property ''' <summary> ''' Gets the ordinal. ''' </summary> Public NotOverridable Overrides ReadOnly Property Ordinal As Integer Get Return _ordinal End Get End Property ''' <summary> ''' Gets the type. ''' </summary> Public NotOverridable Overrides ReadOnly Property Type As TypeSymbol Get Return _type End Get End Property ''' <summary> ''' Gets the name. ''' </summary> Public NotOverridable Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend NotOverridable Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) Dim compilation = Me.DeclaringCompilation If Type.ContainsTupleNames() AndAlso compilation.HasTupleNamesAttributes Then AddSynthesizedAttribute(attributes, compilation.SynthesizeTupleNamesAttribute(Type)) End If End Sub End Class ''' <summary> ''' Base class for synthesized parameter symbols of methods that have been synthesized. E.g. the parameters of delegate methods ''' </summary> Friend Class SynthesizedParameterSymbol Inherits SynthesizedParameterSimpleSymbol Private ReadOnly _isByRef As Boolean Private ReadOnly _isOptional As Boolean Private ReadOnly _defaultValue As ConstantValue ''' <summary> ''' Initializes a new instance of the <see cref="SynthesizedParameterSymbol" /> class. ''' </summary> ''' <param name="container">The containing symbol</param> ''' <param name="type">The type of this parameter</param> ''' <param name="ordinal">The ordinal number of this parameter</param> ''' <param name="isByRef">Whether the parameter is ByRef or not</param> ''' <param name="name">The name of this parameter</param> Public Sub New(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, Optional name As String = "") Me.New(container, type, ordinal, isByRef, name, False, Nothing) End Sub ''' <summary> ''' Initializes a new instance of the <see cref="SynthesizedParameterSymbol" /> class. ''' </summary> ''' <param name="container">The containing symbol</param> ''' <param name="type">The type of this parameter</param> ''' <param name="ordinal">The ordinal number of this parameter</param> ''' <param name="isByRef">Whether the parameter is ByRef or not</param> ''' <param name="name">The name of this parameter</param> Public Sub New(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, isOptional As Boolean, defaultValue As ConstantValue) MyBase.New(container, type, ordinal, name) Me._isByRef = isByRef Me._isOptional = isOptional Me._defaultValue = defaultValue End Sub Public Shared Function Create(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier) ) As SynthesizedParameterSymbol If customModifiers.IsEmpty AndAlso refCustomModifiers.IsEmpty Then Return New SynthesizedParameterSymbol(container, type, ordinal, isByRef, name, isOptional:=False, defaultValue:=Nothing) End If Return New SynthesizedParameterSymbolWithCustomModifiers(container, type, ordinal, isByRef, name, customModifiers, refCustomModifiers) End Function Friend Shared Function CreateSetAccessorValueParameter(setter As MethodSymbol, propertySymbol As PropertySymbol, parameterName As String) As ParameterSymbol Dim valueParameterType As TypeSymbol = propertySymbol.Type Dim valueParameterCustomModifiers = propertySymbol.TypeCustomModifiers Dim overriddenMethod = setter.OverriddenMethod If overriddenMethod IsNot Nothing Then Dim overriddenParameter = overriddenMethod.Parameters(propertySymbol.ParameterCount) If overriddenParameter.Type.IsSameTypeIgnoringAll(valueParameterType) Then valueParameterType = overriddenParameter.Type valueParameterCustomModifiers = overriddenParameter.CustomModifiers End If End If If valueParameterCustomModifiers.IsEmpty Then Return New SynthesizedParameterSimpleSymbol(setter, valueParameterType, propertySymbol.ParameterCount, parameterName) End If Return New SynthesizedParameterSymbolWithCustomModifiers(setter, valueParameterType, propertySymbol.ParameterCount, False, parameterName, valueParameterCustomModifiers, ImmutableArray(Of CustomModifier).Empty) ' Never ByRef End Function ''' <summary> ''' Gets a value indicating whether this instance is by ref. ''' </summary> ''' <value> ''' <c>true</c> if this instance is by ref; otherwise, <c>false</c>. ''' </value> Public NotOverridable Overrides ReadOnly Property IsByRef As Boolean Get Return _isByRef End Get End Property ''' <summary> ''' True if the argument value must be included in the marshalled arguments passed to a remote callee only if it is different from the default value (if there is one). ''' </summary> Public NotOverridable Overrides ReadOnly Property IsOptional As Boolean Get Return _isOptional End Get End Property ''' <summary> ''' A compile time constant value that should be supplied as the corresponding argument value by callers that do not explicitly specify an argument value for this parameter. ''' </summary> Friend NotOverridable Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get Return _defaultValue End Get End Property ''' <summary> ''' True if the parameter has a default value that should be supplied as the argument value by a caller for which the argument value has not been explicitly specified. ''' </summary> Public NotOverridable Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return _defaultValue IsNot Nothing End Get End Property End Class Friend Class SynthesizedParameterSymbolWithCustomModifiers Inherits SynthesizedParameterSymbol Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly _refCustomModifiers As ImmutableArray(Of CustomModifier) ''' <summary> ''' Initializes a new instance of the <see cref="SynthesizedParameterSymbolWithCustomModifiers" /> class. ''' </summary> ''' <param name="container">The containing symbol</param> ''' <param name="type">The type of this parameter</param> ''' <param name="ordinal">The ordinal number of this parameter</param> ''' <param name="isByRef">Whether the parameter is ByRef or not</param> ''' <param name="name">The name of this parameter</param> ''' <param name="customModifiers">The custom modifiers of this parameter type</param> ''' <param name="refCustomModifiers">The custom modifiers of ref modifier</param> Public Sub New(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) MyBase.New(container, type, ordinal, isByRef, name, isOptional:=False, defaultValue:=Nothing) Debug.Assert(Not customModifiers.IsEmpty OrElse Not refCustomModifiers.IsEmpty) Me._customModifiers = customModifiers Me._refCustomModifiers = refCustomModifiers Debug.Assert(Me._refCustomModifiers.IsEmpty OrElse Me.IsByRef) End Sub ''' <summary> ''' The list of custom modifiers, if any, associated with the parameter. Evaluate this property only if IsModified is true. ''' </summary> Public NotOverridable Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._customModifiers End Get End Property Public NotOverridable Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._refCustomModifiers End Get End Property End Class ''' <summary> ''' Extends SynthesizedParameterSymbol to also accept a location ''' </summary> Friend NotInheritable Class SynthesizedParameterWithLocationSymbol Inherits SynthesizedParameterSymbol Private ReadOnly _locations As ImmutableArray(Of Location) Public Sub New(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, location As Location) MyBase.New(container, type, ordinal, isByRef, name) Me._locations = ImmutableArray.Create(Of location)(location) End Sub Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return Me._locations End Get End Property 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 Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Base (simplified) class for synthesized parameter symbols of methods that have been synthesized. E.g. the parameters of delegate methods ''' </summary> Friend Class SynthesizedParameterSimpleSymbol Inherits ParameterSymbol Protected ReadOnly _container As MethodSymbol Protected ReadOnly _type As TypeSymbol Protected ReadOnly _ordinal As Integer Protected ReadOnly _name As String ''' <summary> ''' Initializes a new instance of the <see cref="SynthesizedParameterSymbol" /> class. ''' </summary> ''' <param name="container">The containing symbol</param> ''' <param name="type">The type of this parameter</param> ''' <param name="ordinal">The ordinal number of this parameter</param> ''' <param name="name">The name of this parameter</param> Public Sub New(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, name As String) Me._container = container Me._type = type Me._ordinal = ordinal Me._name = name End Sub ''' <summary> ''' Gets the containing symbol. ''' </summary> Public NotOverridable Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me._container End Get End Property ''' <summary> ''' The list of custom modifiers, if any, associated with the parameter. Evaluate this property only if IsModified is true. ''' </summary> Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property ''' <summary> ''' A compile time constant value that should be supplied as the corresponding argument value by callers that do not explicitly specify an argument value for this parameter. ''' </summary> Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get Return Nothing End Get End Property ''' <summary> ''' True if the parameter has a default value that should be supplied as the argument value by a caller for which the argument value has not been explicitly specified. ''' </summary> Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is by ref. ''' </summary> ''' <value> ''' <c>true</c> if this instance is by ref; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsByRef As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsMetadataIn As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsMetadataOut As Boolean Get Return False End Get End Property Friend Shared Function IsMarshalAsAttributeApplicable(propertySetter As MethodSymbol) As Boolean Debug.Assert(propertySetter.MethodKind = MethodKind.PropertySet) Return propertySetter.ContainingType.IsInterface End Function Friend Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData Get ' Dev11 uses marshalling data of a return type of the containing method for the Value parameter ' of an interface property setter. Dim method = DirectCast(Me.ContainingSymbol, MethodSymbol) If method.MethodKind = MethodKind.PropertySet AndAlso IsMarshalAsAttributeApplicable(method) Then Return DirectCast(method.AssociatedSymbol, SourcePropertySymbol).ReturnTypeMarshallingInformation End If Return Nothing End Get End Property Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get Return IsByRef End Get End Property Friend Overrides ReadOnly Property HasOptionCompare As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property CallerArgumentExpressionParameterIndex As Integer Get Return -1 End Get End Property ''' <summary> ''' True if the argument value must be included in the marshalled arguments passed to a remote callee only if it is different from the default value (if there is one). ''' </summary> Public Overrides ReadOnly Property IsOptional As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is param array. ''' </summary> ''' <value> ''' <c>true</c> if this instance is param array; otherwise, <c>false</c>. ''' </value> Public Overrides ReadOnly Property IsParamArray As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether the symbol was generated by the compiler ''' rather than declared explicitly. ''' </summary> Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property ''' <summary> ''' A potentially empty collection of locations that correspond to this instance. ''' </summary> Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property ''' <summary> ''' Gets the ordinal. ''' </summary> Public NotOverridable Overrides ReadOnly Property Ordinal As Integer Get Return _ordinal End Get End Property ''' <summary> ''' Gets the type. ''' </summary> Public NotOverridable Overrides ReadOnly Property Type As TypeSymbol Get Return _type End Get End Property ''' <summary> ''' Gets the name. ''' </summary> Public NotOverridable Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend NotOverridable Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) Dim compilation = Me.DeclaringCompilation If Type.ContainsTupleNames() AndAlso compilation.HasTupleNamesAttributes Then AddSynthesizedAttribute(attributes, compilation.SynthesizeTupleNamesAttribute(Type)) End If End Sub End Class ''' <summary> ''' Base class for synthesized parameter symbols of methods that have been synthesized. E.g. the parameters of delegate methods ''' </summary> Friend Class SynthesizedParameterSymbol Inherits SynthesizedParameterSimpleSymbol Private ReadOnly _isByRef As Boolean Private ReadOnly _isOptional As Boolean Private ReadOnly _defaultValue As ConstantValue ''' <summary> ''' Initializes a new instance of the <see cref="SynthesizedParameterSymbol" /> class. ''' </summary> ''' <param name="container">The containing symbol</param> ''' <param name="type">The type of this parameter</param> ''' <param name="ordinal">The ordinal number of this parameter</param> ''' <param name="isByRef">Whether the parameter is ByRef or not</param> ''' <param name="name">The name of this parameter</param> Public Sub New(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, Optional name As String = "") Me.New(container, type, ordinal, isByRef, name, False, Nothing) End Sub ''' <summary> ''' Initializes a new instance of the <see cref="SynthesizedParameterSymbol" /> class. ''' </summary> ''' <param name="container">The containing symbol</param> ''' <param name="type">The type of this parameter</param> ''' <param name="ordinal">The ordinal number of this parameter</param> ''' <param name="isByRef">Whether the parameter is ByRef or not</param> ''' <param name="name">The name of this parameter</param> Public Sub New(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, isOptional As Boolean, defaultValue As ConstantValue) MyBase.New(container, type, ordinal, name) Me._isByRef = isByRef Me._isOptional = isOptional Me._defaultValue = defaultValue End Sub Public Shared Function Create(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier) ) As SynthesizedParameterSymbol If customModifiers.IsEmpty AndAlso refCustomModifiers.IsEmpty Then Return New SynthesizedParameterSymbol(container, type, ordinal, isByRef, name, isOptional:=False, defaultValue:=Nothing) End If Return New SynthesizedParameterSymbolWithCustomModifiers(container, type, ordinal, isByRef, name, customModifiers, refCustomModifiers) End Function Friend Shared Function CreateSetAccessorValueParameter(setter As MethodSymbol, propertySymbol As PropertySymbol, parameterName As String) As ParameterSymbol Dim valueParameterType As TypeSymbol = propertySymbol.Type Dim valueParameterCustomModifiers = propertySymbol.TypeCustomModifiers Dim overriddenMethod = setter.OverriddenMethod If overriddenMethod IsNot Nothing Then Dim overriddenParameter = overriddenMethod.Parameters(propertySymbol.ParameterCount) If overriddenParameter.Type.IsSameTypeIgnoringAll(valueParameterType) Then valueParameterType = overriddenParameter.Type valueParameterCustomModifiers = overriddenParameter.CustomModifiers End If End If If valueParameterCustomModifiers.IsEmpty Then Return New SynthesizedParameterSimpleSymbol(setter, valueParameterType, propertySymbol.ParameterCount, parameterName) End If Return New SynthesizedParameterSymbolWithCustomModifiers(setter, valueParameterType, propertySymbol.ParameterCount, False, parameterName, valueParameterCustomModifiers, ImmutableArray(Of CustomModifier).Empty) ' Never ByRef End Function ''' <summary> ''' Gets a value indicating whether this instance is by ref. ''' </summary> ''' <value> ''' <c>true</c> if this instance is by ref; otherwise, <c>false</c>. ''' </value> Public NotOverridable Overrides ReadOnly Property IsByRef As Boolean Get Return _isByRef End Get End Property ''' <summary> ''' True if the argument value must be included in the marshalled arguments passed to a remote callee only if it is different from the default value (if there is one). ''' </summary> Public NotOverridable Overrides ReadOnly Property IsOptional As Boolean Get Return _isOptional End Get End Property ''' <summary> ''' A compile time constant value that should be supplied as the corresponding argument value by callers that do not explicitly specify an argument value for this parameter. ''' </summary> Friend NotOverridable Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get Return _defaultValue End Get End Property ''' <summary> ''' True if the parameter has a default value that should be supplied as the argument value by a caller for which the argument value has not been explicitly specified. ''' </summary> Public NotOverridable Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return _defaultValue IsNot Nothing End Get End Property End Class Friend Class SynthesizedParameterSymbolWithCustomModifiers Inherits SynthesizedParameterSymbol Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly _refCustomModifiers As ImmutableArray(Of CustomModifier) ''' <summary> ''' Initializes a new instance of the <see cref="SynthesizedParameterSymbolWithCustomModifiers" /> class. ''' </summary> ''' <param name="container">The containing symbol</param> ''' <param name="type">The type of this parameter</param> ''' <param name="ordinal">The ordinal number of this parameter</param> ''' <param name="isByRef">Whether the parameter is ByRef or not</param> ''' <param name="name">The name of this parameter</param> ''' <param name="customModifiers">The custom modifiers of this parameter type</param> ''' <param name="refCustomModifiers">The custom modifiers of ref modifier</param> Public Sub New(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) MyBase.New(container, type, ordinal, isByRef, name, isOptional:=False, defaultValue:=Nothing) Debug.Assert(Not customModifiers.IsEmpty OrElse Not refCustomModifiers.IsEmpty) Me._customModifiers = customModifiers Me._refCustomModifiers = refCustomModifiers Debug.Assert(Me._refCustomModifiers.IsEmpty OrElse Me.IsByRef) End Sub ''' <summary> ''' The list of custom modifiers, if any, associated with the parameter. Evaluate this property only if IsModified is true. ''' </summary> Public NotOverridable Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._customModifiers End Get End Property Public NotOverridable Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._refCustomModifiers End Get End Property End Class ''' <summary> ''' Extends SynthesizedParameterSymbol to also accept a location ''' </summary> Friend NotInheritable Class SynthesizedParameterWithLocationSymbol Inherits SynthesizedParameterSymbol Private ReadOnly _locations As ImmutableArray(Of Location) Public Sub New(container As MethodSymbol, type As TypeSymbol, ordinal As Integer, isByRef As Boolean, name As String, location As Location) MyBase.New(container, type, ordinal, isByRef, name) Me._locations = ImmutableArray.Create(Of location)(location) End Sub Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return Me._locations End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/CatchKeywordRecommender.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.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Catch" keyword for the statement context ''' </summary> Friend Class CatchKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Catch", VBFeaturesResources.Introduces_a_statement_block_to_be_run_if_the_specified_exception_occurs_inside_a_Try_block)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If Not context.IsMultiLineStatementContext Then Return ImmutableArray(Of RecommendedKeyword).Empty End If ' We'll recommend a catch statement if it's within a Try block or a Catch block, because you could be ' trying to start one in either location Return If(context.IsInStatementBlockOfKind(SyntaxKind.TryBlock, SyntaxKind.CatchBlock) AndAlso Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock), s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) 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.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Catch" keyword for the statement context ''' </summary> Friend Class CatchKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Catch", VBFeaturesResources.Introduces_a_statement_block_to_be_run_if_the_specified_exception_occurs_inside_a_Try_block)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If Not context.IsMultiLineStatementContext Then Return ImmutableArray(Of RecommendedKeyword).Empty End If ' We'll recommend a catch statement if it's within a Try block or a Catch block, because you could be ' trying to start one in either location Return If(context.IsInStatementBlockOfKind(SyntaxKind.TryBlock, SyntaxKind.CatchBlock) AndAlso Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock), s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/SymbolUsageAnalysis/SymbolUsageAnalysis.DataFlowAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis.SymbolUsageAnalysis { internal static partial class SymbolUsageAnalysis { /// <summary> /// Dataflow analysis to compute symbol usage information (i.e. reads/writes) for locals/parameters /// in a given control flow graph, along with the information of whether or not the writes /// may be read on some control flow path. /// </summary> private sealed partial class DataFlowAnalyzer : DataFlowAnalyzer<BasicBlockAnalysisData> { private readonly FlowGraphAnalysisData _analysisData; private DataFlowAnalyzer(ControlFlowGraph cfg, ISymbol owningSymbol) => _analysisData = FlowGraphAnalysisData.Create(cfg, owningSymbol, AnalyzeLocalFunctionOrLambdaInvocation); private DataFlowAnalyzer( ControlFlowGraph cfg, IMethodSymbol lambdaOrLocalFunction, FlowGraphAnalysisData parentAnalysisData) { _analysisData = FlowGraphAnalysisData.Create(cfg, lambdaOrLocalFunction, parentAnalysisData); var entryBlockAnalysisData = GetEmptyAnalysisData(); entryBlockAnalysisData.SetAnalysisDataFrom(parentAnalysisData.CurrentBlockAnalysisData); _analysisData.SetBlockAnalysisData(cfg.EntryBlock(), entryBlockAnalysisData); } public static SymbolUsageResult RunAnalysis(ControlFlowGraph cfg, ISymbol owningSymbol, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var analyzer = new DataFlowAnalyzer(cfg, owningSymbol); _ = CustomDataFlowAnalysis<BasicBlockAnalysisData>.Run(cfg, analyzer, cancellationToken); return analyzer._analysisData.ToResult(); } public override void Dispose() => _analysisData.Dispose(); private static BasicBlockAnalysisData AnalyzeLocalFunctionOrLambdaInvocation( IMethodSymbol localFunctionOrLambda, ControlFlowGraph cfg, AnalysisData parentAnalysisData, CancellationToken cancellationToken) { Debug.Assert(localFunctionOrLambda.IsLocalFunction() || localFunctionOrLambda.IsAnonymousFunction()); cancellationToken.ThrowIfCancellationRequested(); using var analyzer = new DataFlowAnalyzer(cfg, localFunctionOrLambda, (FlowGraphAnalysisData)parentAnalysisData); var resultBlockAnalysisData = CustomDataFlowAnalysis<BasicBlockAnalysisData>.Run(cfg, analyzer, cancellationToken); if (resultBlockAnalysisData == null) { // Unreachable exit block from lambda/local. // So use our current analysis data. return parentAnalysisData.CurrentBlockAnalysisData; } // We need to return a cloned basic block analysis data as disposing the DataFlowAnalyzer // created above will dispose all basic block analysis data instances allocated by it. var clonedBasicBlockData = parentAnalysisData.CreateBlockAnalysisData(); clonedBasicBlockData.SetAnalysisDataFrom(resultBlockAnalysisData); return clonedBasicBlockData; } // Don't analyze blocks which are unreachable, as any write // in such a block which has a read outside will be marked redundant, which will just be noise for users. // For example, // int x; // if (true) // x = 0; // else // x = 1; // This will be marked redundant if "AnalyzeUnreachableBlocks = true" // return x; public override bool AnalyzeUnreachableBlocks => false; public override BasicBlockAnalysisData AnalyzeBlock(BasicBlock basicBlock, CancellationToken cancellationToken) { BeforeBlockAnalysis(); Walker.AnalyzeOperationsAndUpdateData(_analysisData.OwningSymbol, basicBlock.Operations, _analysisData, cancellationToken); AfterBlockAnalysis(); return _analysisData.CurrentBlockAnalysisData; // Local functions. void BeforeBlockAnalysis() { // Initialize current block analysis data. _analysisData.SetCurrentBlockAnalysisDataFrom(basicBlock, cancellationToken); // At start of entry block, handle parameter definitions from method declaration. if (basicBlock.Kind == BasicBlockKind.Entry) { _analysisData.SetAnalysisDataOnEntryBlockStart(); } } void AfterBlockAnalysis() { // If we are exiting the control flow graph, handle ref/out parameter definitions from method declaration. if (basicBlock.FallThroughSuccessor?.Destination == null && basicBlock.ConditionalSuccessor?.Destination == null) { _analysisData.SetAnalysisDataOnMethodExit(); } } } public override BasicBlockAnalysisData AnalyzeNonConditionalBranch( BasicBlock basicBlock, BasicBlockAnalysisData currentBlockAnalysisData, CancellationToken cancellationToken) => AnalyzeBranch(basicBlock.FallThroughSuccessor, basicBlock, currentBlockAnalysisData, cancellationToken); public override (BasicBlockAnalysisData fallThroughSuccessorData, BasicBlockAnalysisData conditionalSuccessorData) AnalyzeConditionalBranch( BasicBlock basicBlock, BasicBlockAnalysisData currentAnalysisData, CancellationToken cancellationToken) { // Ensure that we use distinct input BasicBlockAnalysisData instances with identical analysis data for both AnalyzeBranch invocations. using var savedCurrentAnalysisData = BasicBlockAnalysisData.GetInstance(); savedCurrentAnalysisData.SetAnalysisDataFrom(currentAnalysisData); var newCurrentAnalysisData = AnalyzeBranch(basicBlock.FallThroughSuccessor, basicBlock, currentAnalysisData, cancellationToken); // Ensure that we use different instances of block analysis data for fall through successor and conditional successor. _analysisData.AdditionalConditionalBranchAnalysisData.SetAnalysisDataFrom(newCurrentAnalysisData); var fallThroughSuccessorData = _analysisData.AdditionalConditionalBranchAnalysisData; var conditionalSuccessorData = AnalyzeBranch(basicBlock.ConditionalSuccessor, basicBlock, savedCurrentAnalysisData, cancellationToken); return (fallThroughSuccessorData, conditionalSuccessorData); } private BasicBlockAnalysisData AnalyzeBranch( ControlFlowBranch branch, BasicBlock basicBlock, BasicBlockAnalysisData currentBlockAnalysisData, CancellationToken cancellationToken) { // Initialize current analysis data _analysisData.SetCurrentBlockAnalysisDataFrom(currentBlockAnalysisData); // Analyze the branch value var operations = SpecializedCollections.SingletonEnumerable(basicBlock.BranchValue); Walker.AnalyzeOperationsAndUpdateData(_analysisData.OwningSymbol, operations, _analysisData, cancellationToken); ProcessOutOfScopeLocals(); return _analysisData.CurrentBlockAnalysisData; // Local functions void ProcessOutOfScopeLocals() { if (branch == null) { return; } if (basicBlock.EnclosingRegion.Kind == ControlFlowRegionKind.Catch && !branch.FinallyRegions.IsEmpty) { // Bail out for branches from the catch block // as the locals are still accessible in the finally region. return; } foreach (var region in branch.LeavingRegions) { foreach (var local in region.Locals) { _analysisData.CurrentBlockAnalysisData.Clear(local); } if (region.Kind == ControlFlowRegionKind.TryAndFinally) { // Locals defined in the outer regions of try/finally might be used in finally region. break; } } } } public override BasicBlockAnalysisData GetCurrentAnalysisData(BasicBlock basicBlock) => _analysisData.GetBlockAnalysisData(basicBlock) ?? GetEmptyAnalysisData(); public override BasicBlockAnalysisData GetEmptyAnalysisData() => _analysisData.CreateBlockAnalysisData(); public override void SetCurrentAnalysisData(BasicBlock basicBlock, BasicBlockAnalysisData data, CancellationToken cancellationToken) => _analysisData.SetBlockAnalysisDataFrom(basicBlock, data, cancellationToken); public override bool IsEqual(BasicBlockAnalysisData analysisData1, BasicBlockAnalysisData analysisData2) => analysisData1 == null ? analysisData2 == null : analysisData1.Equals(analysisData2); public override BasicBlockAnalysisData Merge( BasicBlockAnalysisData analysisData1, BasicBlockAnalysisData analysisData2, CancellationToken cancellationToken) => BasicBlockAnalysisData.Merge(analysisData1, analysisData2, _analysisData.TrackAllocatedBlockAnalysisData); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis.SymbolUsageAnalysis { internal static partial class SymbolUsageAnalysis { /// <summary> /// Dataflow analysis to compute symbol usage information (i.e. reads/writes) for locals/parameters /// in a given control flow graph, along with the information of whether or not the writes /// may be read on some control flow path. /// </summary> private sealed partial class DataFlowAnalyzer : DataFlowAnalyzer<BasicBlockAnalysisData> { private readonly FlowGraphAnalysisData _analysisData; private DataFlowAnalyzer(ControlFlowGraph cfg, ISymbol owningSymbol) => _analysisData = FlowGraphAnalysisData.Create(cfg, owningSymbol, AnalyzeLocalFunctionOrLambdaInvocation); private DataFlowAnalyzer( ControlFlowGraph cfg, IMethodSymbol lambdaOrLocalFunction, FlowGraphAnalysisData parentAnalysisData) { _analysisData = FlowGraphAnalysisData.Create(cfg, lambdaOrLocalFunction, parentAnalysisData); var entryBlockAnalysisData = GetEmptyAnalysisData(); entryBlockAnalysisData.SetAnalysisDataFrom(parentAnalysisData.CurrentBlockAnalysisData); _analysisData.SetBlockAnalysisData(cfg.EntryBlock(), entryBlockAnalysisData); } public static SymbolUsageResult RunAnalysis(ControlFlowGraph cfg, ISymbol owningSymbol, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using var analyzer = new DataFlowAnalyzer(cfg, owningSymbol); _ = CustomDataFlowAnalysis<BasicBlockAnalysisData>.Run(cfg, analyzer, cancellationToken); return analyzer._analysisData.ToResult(); } public override void Dispose() => _analysisData.Dispose(); private static BasicBlockAnalysisData AnalyzeLocalFunctionOrLambdaInvocation( IMethodSymbol localFunctionOrLambda, ControlFlowGraph cfg, AnalysisData parentAnalysisData, CancellationToken cancellationToken) { Debug.Assert(localFunctionOrLambda.IsLocalFunction() || localFunctionOrLambda.IsAnonymousFunction()); cancellationToken.ThrowIfCancellationRequested(); using var analyzer = new DataFlowAnalyzer(cfg, localFunctionOrLambda, (FlowGraphAnalysisData)parentAnalysisData); var resultBlockAnalysisData = CustomDataFlowAnalysis<BasicBlockAnalysisData>.Run(cfg, analyzer, cancellationToken); if (resultBlockAnalysisData == null) { // Unreachable exit block from lambda/local. // So use our current analysis data. return parentAnalysisData.CurrentBlockAnalysisData; } // We need to return a cloned basic block analysis data as disposing the DataFlowAnalyzer // created above will dispose all basic block analysis data instances allocated by it. var clonedBasicBlockData = parentAnalysisData.CreateBlockAnalysisData(); clonedBasicBlockData.SetAnalysisDataFrom(resultBlockAnalysisData); return clonedBasicBlockData; } // Don't analyze blocks which are unreachable, as any write // in such a block which has a read outside will be marked redundant, which will just be noise for users. // For example, // int x; // if (true) // x = 0; // else // x = 1; // This will be marked redundant if "AnalyzeUnreachableBlocks = true" // return x; public override bool AnalyzeUnreachableBlocks => false; public override BasicBlockAnalysisData AnalyzeBlock(BasicBlock basicBlock, CancellationToken cancellationToken) { BeforeBlockAnalysis(); Walker.AnalyzeOperationsAndUpdateData(_analysisData.OwningSymbol, basicBlock.Operations, _analysisData, cancellationToken); AfterBlockAnalysis(); return _analysisData.CurrentBlockAnalysisData; // Local functions. void BeforeBlockAnalysis() { // Initialize current block analysis data. _analysisData.SetCurrentBlockAnalysisDataFrom(basicBlock, cancellationToken); // At start of entry block, handle parameter definitions from method declaration. if (basicBlock.Kind == BasicBlockKind.Entry) { _analysisData.SetAnalysisDataOnEntryBlockStart(); } } void AfterBlockAnalysis() { // If we are exiting the control flow graph, handle ref/out parameter definitions from method declaration. if (basicBlock.FallThroughSuccessor?.Destination == null && basicBlock.ConditionalSuccessor?.Destination == null) { _analysisData.SetAnalysisDataOnMethodExit(); } } } public override BasicBlockAnalysisData AnalyzeNonConditionalBranch( BasicBlock basicBlock, BasicBlockAnalysisData currentBlockAnalysisData, CancellationToken cancellationToken) => AnalyzeBranch(basicBlock.FallThroughSuccessor, basicBlock, currentBlockAnalysisData, cancellationToken); public override (BasicBlockAnalysisData fallThroughSuccessorData, BasicBlockAnalysisData conditionalSuccessorData) AnalyzeConditionalBranch( BasicBlock basicBlock, BasicBlockAnalysisData currentAnalysisData, CancellationToken cancellationToken) { // Ensure that we use distinct input BasicBlockAnalysisData instances with identical analysis data for both AnalyzeBranch invocations. using var savedCurrentAnalysisData = BasicBlockAnalysisData.GetInstance(); savedCurrentAnalysisData.SetAnalysisDataFrom(currentAnalysisData); var newCurrentAnalysisData = AnalyzeBranch(basicBlock.FallThroughSuccessor, basicBlock, currentAnalysisData, cancellationToken); // Ensure that we use different instances of block analysis data for fall through successor and conditional successor. _analysisData.AdditionalConditionalBranchAnalysisData.SetAnalysisDataFrom(newCurrentAnalysisData); var fallThroughSuccessorData = _analysisData.AdditionalConditionalBranchAnalysisData; var conditionalSuccessorData = AnalyzeBranch(basicBlock.ConditionalSuccessor, basicBlock, savedCurrentAnalysisData, cancellationToken); return (fallThroughSuccessorData, conditionalSuccessorData); } private BasicBlockAnalysisData AnalyzeBranch( ControlFlowBranch branch, BasicBlock basicBlock, BasicBlockAnalysisData currentBlockAnalysisData, CancellationToken cancellationToken) { // Initialize current analysis data _analysisData.SetCurrentBlockAnalysisDataFrom(currentBlockAnalysisData); // Analyze the branch value var operations = SpecializedCollections.SingletonEnumerable(basicBlock.BranchValue); Walker.AnalyzeOperationsAndUpdateData(_analysisData.OwningSymbol, operations, _analysisData, cancellationToken); ProcessOutOfScopeLocals(); return _analysisData.CurrentBlockAnalysisData; // Local functions void ProcessOutOfScopeLocals() { if (branch == null) { return; } if (basicBlock.EnclosingRegion.Kind == ControlFlowRegionKind.Catch && !branch.FinallyRegions.IsEmpty) { // Bail out for branches from the catch block // as the locals are still accessible in the finally region. return; } foreach (var region in branch.LeavingRegions) { foreach (var local in region.Locals) { _analysisData.CurrentBlockAnalysisData.Clear(local); } if (region.Kind == ControlFlowRegionKind.TryAndFinally) { // Locals defined in the outer regions of try/finally might be used in finally region. break; } } } } public override BasicBlockAnalysisData GetCurrentAnalysisData(BasicBlock basicBlock) => _analysisData.GetBlockAnalysisData(basicBlock) ?? GetEmptyAnalysisData(); public override BasicBlockAnalysisData GetEmptyAnalysisData() => _analysisData.CreateBlockAnalysisData(); public override void SetCurrentAnalysisData(BasicBlock basicBlock, BasicBlockAnalysisData data, CancellationToken cancellationToken) => _analysisData.SetBlockAnalysisDataFrom(basicBlock, data, cancellationToken); public override bool IsEqual(BasicBlockAnalysisData analysisData1, BasicBlockAnalysisData analysisData2) => analysisData1 == null ? analysisData2 == null : analysisData1.Equals(analysisData2); public override BasicBlockAnalysisData Merge( BasicBlockAnalysisData analysisData1, BasicBlockAnalysisData analysisData2, CancellationToken cancellationToken) => BasicBlockAnalysisData.Merge(analysisData1, analysisData2, _analysisData.TrackAllocatedBlockAnalysisData); } } }
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Workspaces/Core/Portable/Classification/ISemanticClassificationCacheService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { /// <summary> /// Service that can retrieve semantic classifications for a document cached during a previous session. This is /// intended to help populate semantic classifications for a host during the time while a solution is loading and /// semantics may be incomplete or unavailable. /// </summary> internal interface ISemanticClassificationCacheService : IWorkspaceService { /// <summary> /// Tries to get cached semantic classifications for the specified document and the specified <paramref /// name="textSpan"/>. Will return a <c>default</c> array not able to. An empty array indicates that there /// were cached classifications, but none that intersected the provided <paramref name="textSpan"/>. /// </summary> /// <param name="checksum">Pass in <see cref="DocumentStateChecksums.Text"/>. This will ensure that the cached /// classifications are only returned if they match the content the file currently has.</param> Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync( DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(ISemanticClassificationCacheService)), Shared] internal class DefaultSemanticClassificationCacheService : ISemanticClassificationCacheService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultSemanticClassificationCacheService() { } public Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync(DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Default<ImmutableArray<ClassifiedSpan>>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { /// <summary> /// Service that can retrieve semantic classifications for a document cached during a previous session. This is /// intended to help populate semantic classifications for a host during the time while a solution is loading and /// semantics may be incomplete or unavailable. /// </summary> internal interface ISemanticClassificationCacheService : IWorkspaceService { /// <summary> /// Tries to get cached semantic classifications for the specified document and the specified <paramref /// name="textSpan"/>. Will return a <c>default</c> array not able to. An empty array indicates that there /// were cached classifications, but none that intersected the provided <paramref name="textSpan"/>. /// </summary> /// <param name="checksum">Pass in <see cref="DocumentStateChecksums.Text"/>. This will ensure that the cached /// classifications are only returned if they match the content the file currently has.</param> Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync( DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(ISemanticClassificationCacheService)), Shared] internal class DefaultSemanticClassificationCacheService : ISemanticClassificationCacheService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultSemanticClassificationCacheService() { } public Task<ImmutableArray<ClassifiedSpan>> GetCachedSemanticClassificationsAsync(DocumentKey documentKey, TextSpan textSpan, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Default<ImmutableArray<ClassifiedSpan>>(); } }
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Workspaces/CSharpTest/CSharpSyntaxFactsServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public sealed class CSharpSyntaxFactsServiceTests { private static bool IsQueryKeyword(string markup) { MarkupTestFile.GetPosition(markup, out var code, out int position); var tree = SyntaxFactory.ParseSyntaxTree(code); var token = tree.GetRoot().FindToken(position); var service = CSharpSyntaxFacts.Instance; return service.IsQueryKeyword(token); } private static string WrapInMethod(string methodBody) { return $@" class C {{ void M() {{ {methodBody} }} }}"; } [Fact] public void IsQueryKeyword_From() { Assert.True(IsQueryKeyword(WrapInMethod(@" var result = $$from var1 in collection1"))); } [Fact] public void IsQueryKeyword_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var result = from var1 $$in collection1"))); } [Fact] public void IsQueryKeyword_Where() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customerOrders = from cust in customers $$where cust.CustomerID = 1"))); } [Fact] public void IsQueryKeyword_Select() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customerOrders = from cust in customers from ord in orders where cust.CustomerID == ord.CustomerID $$select cust.CompanyName, ord.OrderDate"))); } [Fact] public void IsQueryKeyword_GroupBy_Group() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers $$group cust by cust.Country into g"))); } [Fact] public void IsQueryKeyword_GroupBy_By() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers group cust $$by cust.Country into g"))); } [Fact] public void IsQueryKeyword_Into() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers group cust by cust.Country $$into g"))); } [Fact] public void IsQueryKeyword_GroupJoin_Join() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people $$join pet in pets on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet $$in pets on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_On() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets $$on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_Equals() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person $$equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_Into() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person equals pet.Owner $$into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_Join_Join() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people $$join pet in pets on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet $$in pets on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_On() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets $$on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_Equals() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person $$equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Let() { Assert.True(IsQueryKeyword(WrapInMethod(@" var discountedProducts = from prod in products $$let discount = prod.UnitPrice * 0.1 where discount >= 50 select new { prod.ProductName, prod.UnitPrice, Discount }"))); } [Fact] public void IsQueryKeyword_OrderBy_OrderBy() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books $$orderby book.Price descending, book.Title ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_OrderBy_Descending() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books orderby book.Price $$descending, book.Title ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_OrderBy_Ascending() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books orderby book.Price descending, book.Title $$ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_Not_ForEach_In() { Assert.False(IsQueryKeyword(WrapInMethod(@" foreach (var i $$in new int[0]) { }"))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public sealed class CSharpSyntaxFactsServiceTests { private static bool IsQueryKeyword(string markup) { MarkupTestFile.GetPosition(markup, out var code, out int position); var tree = SyntaxFactory.ParseSyntaxTree(code); var token = tree.GetRoot().FindToken(position); var service = CSharpSyntaxFacts.Instance; return service.IsQueryKeyword(token); } private static string WrapInMethod(string methodBody) { return $@" class C {{ void M() {{ {methodBody} }} }}"; } [Fact] public void IsQueryKeyword_From() { Assert.True(IsQueryKeyword(WrapInMethod(@" var result = $$from var1 in collection1"))); } [Fact] public void IsQueryKeyword_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var result = from var1 $$in collection1"))); } [Fact] public void IsQueryKeyword_Where() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customerOrders = from cust in customers $$where cust.CustomerID = 1"))); } [Fact] public void IsQueryKeyword_Select() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customerOrders = from cust in customers from ord in orders where cust.CustomerID == ord.CustomerID $$select cust.CompanyName, ord.OrderDate"))); } [Fact] public void IsQueryKeyword_GroupBy_Group() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers $$group cust by cust.Country into g"))); } [Fact] public void IsQueryKeyword_GroupBy_By() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers group cust $$by cust.Country into g"))); } [Fact] public void IsQueryKeyword_Into() { Assert.True(IsQueryKeyword(WrapInMethod(@" var customersByCountry = from cust in customers group cust by cust.Country $$into g"))); } [Fact] public void IsQueryKeyword_GroupJoin_Join() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people $$join pet in pets on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet $$in pets on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_On() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets $$on person equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_Equals() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person $$equals pet.Owner into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_GroupJoin_Into() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person equals pet.Owner $$into gj select new { OwnerName = person.FirstName, Pets = gj };"))); } [Fact] public void IsQueryKeyword_Join_Join() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people $$join pet in pets on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_In() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet $$in pets on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_On() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets $$on person equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Join_Equals() { Assert.True(IsQueryKeyword(WrapInMethod(@" var query = from person in people join pet in pets on person $$equals pet.Owner select new { OwnerName = person.FirstName, PetName = pet.Name };"))); } [Fact] public void IsQueryKeyword_Let() { Assert.True(IsQueryKeyword(WrapInMethod(@" var discountedProducts = from prod in products $$let discount = prod.UnitPrice * 0.1 where discount >= 50 select new { prod.ProductName, prod.UnitPrice, Discount }"))); } [Fact] public void IsQueryKeyword_OrderBy_OrderBy() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books $$orderby book.Price descending, book.Title ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_OrderBy_Descending() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books orderby book.Price $$descending, book.Title ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_OrderBy_Ascending() { Assert.True(IsQueryKeyword(WrapInMethod(@" var titlesDescendingPrice = from book in books orderby book.Price descending, book.Title $$ascending, book.Author select new { book.Title, book.Price }"))); } [Fact] public void IsQueryKeyword_Not_ForEach_In() { Assert.False(IsQueryKeyword(WrapInMethod(@" foreach (var i $$in new int[0]) { }"))); } } }
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/VisualStudio/Core/Def/EditorConfigSettings/ServiceProviderExtensions.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.CodeAnalysis; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { internal static class ServiceProviderExtensions { public static bool TryGetService<TService, TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface) where TInterface : class { @interface = sp.GetService<TService, TInterface>(throwOnFailure: false); return @interface is not null; } public static bool TryGetService<TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface) where TInterface : class { @interface = sp.GetService<TInterface>(); return @interface is not null; } public static TInterface? GetService<TInterface>(this IServiceProvider sp) where TInterface : class { return sp.GetService<TInterface, TInterface>(throwOnFailure: false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { internal static class ServiceProviderExtensions { public static bool TryGetService<TService, TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface) where TInterface : class { @interface = sp.GetService<TService, TInterface>(throwOnFailure: false); return @interface is not null; } public static bool TryGetService<TInterface>(this IServiceProvider sp, [NotNullWhen(true)] out TInterface? @interface) where TInterface : class { @interface = sp.GetService<TInterface>(); return @interface is not null; } public static TInterface? GetService<TInterface>(this IServiceProvider sp) where TInterface : class { return sp.GetService<TInterface, TInterface>(throwOnFailure: false); } } }
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/EditorFeatures/CSharpTest/ConvertNamespace/ConvertToFileScopedNamespaceAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertNamespace; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Testing; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNamespace { using VerifyCS = CSharpCodeFixVerifier<ConvertToFileScopedNamespaceDiagnosticAnalyzer, ConvertNamespaceCodeFixProvider>; public class ConvertToFileScopedNamespaceAnalyzerTests { #region Convert To File Scoped [Fact] public async Task TestNoConvertToFileScopedInCSharp9() { var code = @" namespace N { } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestNoConvertToFileScopedInCSharp10WithBlockScopedPreference() { var code = @" namespace N { } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { } ", FixedCode = @" namespace $$N; ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestNoConvertWithMultipleNamespaces() { var code = @" namespace N { } namespace N2 { } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestNoConvertWithNestedNamespaces1() { var code = @" namespace N { namespace N2 { } } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestNoConvertWithTopLevelStatement1() { var code = @" {|CS8805:int i = 0;|} namespace N { } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestNoConvertWithTopLevelStatement2() { var code = @" namespace N { } int i = 0; "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp10, ExpectedDiagnostics = { // /0/Test0.cs(6,1): error CS8803: Top-level statements must precede namespace and type declarations. DiagnosticResult.CompilerError("CS8803").WithSpan(6, 1, 6, 11), // /0/Test0.cs(6,1): error CS8805: Program using top-level statements must be an executable. DiagnosticResult.CompilerError("CS8805").WithSpan(6, 1, 6, 11), }, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithUsing1() { await new VerifyCS.Test { TestCode = @" using System; [|namespace N|] { } ", FixedCode = @" using System; namespace $$N; ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithUsing2() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { using System; } ", FixedCode = @" namespace $$N; using System; ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithClass() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { class C { } } ", FixedCode = @" namespace $$N; class C { } ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithClassWithDocComment() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { /// <summary/> class C { } } ", FixedCode = @" namespace $$N; /// <summary/> class C { } ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithMissingCloseBrace() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { /// <summary/> class C { }{|CS1513:|}", FixedCode = @" namespace N; /// <summary/> class C { }", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithCommentOnOpenCurly() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { // comment class C { } } ", FixedCode = @" namespace $$N; // comment class C { } ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithLeadingComment() { await new VerifyCS.Test { TestCode = @" // copyright [|namespace N|] { class C { } } ", FixedCode = @" // copyright namespace $$N; class C { } ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertNamespace; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Testing; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNamespace { using VerifyCS = CSharpCodeFixVerifier<ConvertToFileScopedNamespaceDiagnosticAnalyzer, ConvertNamespaceCodeFixProvider>; public class ConvertToFileScopedNamespaceAnalyzerTests { #region Convert To File Scoped [Fact] public async Task TestNoConvertToFileScopedInCSharp9() { var code = @" namespace N { } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp9, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestNoConvertToFileScopedInCSharp10WithBlockScopedPreference() { var code = @" namespace N { } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.BlockScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedInCSharp10WithBlockScopedPreference() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { } ", FixedCode = @" namespace $$N; ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestNoConvertWithMultipleNamespaces() { var code = @" namespace N { } namespace N2 { } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestNoConvertWithNestedNamespaces1() { var code = @" namespace N { namespace N2 { } } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestNoConvertWithTopLevelStatement1() { var code = @" {|CS8805:int i = 0;|} namespace N { } "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestNoConvertWithTopLevelStatement2() { var code = @" namespace N { } int i = 0; "; await new VerifyCS.Test { TestCode = code, FixedCode = code, LanguageVersion = LanguageVersion.CSharp10, ExpectedDiagnostics = { // /0/Test0.cs(6,1): error CS8803: Top-level statements must precede namespace and type declarations. DiagnosticResult.CompilerError("CS8803").WithSpan(6, 1, 6, 11), // /0/Test0.cs(6,1): error CS8805: Program using top-level statements must be an executable. DiagnosticResult.CompilerError("CS8805").WithSpan(6, 1, 6, 11), }, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithUsing1() { await new VerifyCS.Test { TestCode = @" using System; [|namespace N|] { } ", FixedCode = @" using System; namespace $$N; ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithUsing2() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { using System; } ", FixedCode = @" namespace $$N; using System; ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithClass() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { class C { } } ", FixedCode = @" namespace $$N; class C { } ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithClassWithDocComment() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { /// <summary/> class C { } } ", FixedCode = @" namespace $$N; /// <summary/> class C { } ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithMissingCloseBrace() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { /// <summary/> class C { }{|CS1513:|}", FixedCode = @" namespace N; /// <summary/> class C { }", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithCommentOnOpenCurly() { await new VerifyCS.Test { TestCode = @" [|namespace N|] { // comment class C { } } ", FixedCode = @" namespace $$N; // comment class C { } ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } [Fact] public async Task TestConvertToFileScopedWithLeadingComment() { await new VerifyCS.Test { TestCode = @" // copyright [|namespace N|] { class C { } } ", FixedCode = @" // copyright namespace $$N; class C { } ", LanguageVersion = LanguageVersion.CSharp10, Options = { { CSharpCodeStyleOptions.NamespaceDeclarations, NamespaceDeclarationPreference.FileScoped } } }.RunAsync(); } #endregion } }
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/SyntaxFacts/VisualBasicSyntaxKinds.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.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxKinds Implements ISyntaxKinds Public Shared ReadOnly Instance As New VisualBasicSyntaxKinds() Protected Sub New() End Sub Public Function Convert(Of TSyntaxKind As Structure)(kind As Integer) As TSyntaxKind Implements ISyntaxKinds.Convert ' Boxing/Unboxing casts from Object to TSyntaxKind will be erased by jit. Return CType(CType(CType(kind, SyntaxKind), Object), TSyntaxKind) End Function Public ReadOnly Property ConflictMarkerTrivia As Integer = SyntaxKind.ConflictMarkerTrivia Implements ISyntaxKinds.ConflictMarkerTrivia Public ReadOnly Property DisabledTextTrivia As Integer = SyntaxKind.DisabledTextTrivia Implements ISyntaxKinds.DisabledTextTrivia Public ReadOnly Property EndOfLineTrivia As Integer = SyntaxKind.EndOfLineTrivia Implements ISyntaxKinds.EndOfLineTrivia Public ReadOnly Property SkippedTokensTrivia As Integer = SyntaxKind.SkippedTokensTrivia Implements ISyntaxKinds.SkippedTokensTrivia Public ReadOnly Property WhitespaceTrivia As Integer = SyntaxKind.WhitespaceTrivia Implements ISyntaxKinds.WhitespaceTrivia Public ReadOnly Property SingleLineCommentTrivia As Integer = SyntaxKind.CommentTrivia Implements ISyntaxKinds.SingleLineCommentTrivia Private ReadOnly Property MultiLineCommentTrivia As Integer? Implements ISyntaxKinds.MultiLineCommentTrivia Public ReadOnly Property CloseBraceToken As Integer = SyntaxKind.CloseBraceToken Implements ISyntaxKinds.CloseBraceToken Public ReadOnly Property ColonToken As Integer = SyntaxKind.ColonToken Implements ISyntaxKinds.ColonToken Public ReadOnly Property CharacterLiteralToken As Integer = SyntaxKind.CharacterLiteralToken Implements ISyntaxKinds.CharacterLiteralToken Public ReadOnly Property DotToken As Integer = SyntaxKind.DotToken Implements ISyntaxKinds.DotToken Public ReadOnly Property InterpolatedStringTextToken As Integer = SyntaxKind.InterpolatedStringTextToken Implements ISyntaxKinds.InterpolatedStringTextToken Public ReadOnly Property QuestionToken As Integer = SyntaxKind.QuestionToken Implements ISyntaxKinds.QuestionToken Public ReadOnly Property StringLiteralToken As Integer = SyntaxKind.StringLiteralToken Implements ISyntaxKinds.StringLiteralToken Public ReadOnly Property IfKeyword As Integer = SyntaxKind.IfKeyword Implements ISyntaxKinds.IfKeyword Public ReadOnly Property GenericName As Integer = SyntaxKind.GenericName Implements ISyntaxKinds.GenericName Public ReadOnly Property IdentifierName As Integer = SyntaxKind.IdentifierName Implements ISyntaxKinds.IdentifierName Public ReadOnly Property QualifiedName As Integer = SyntaxKind.QualifiedName Implements ISyntaxKinds.QualifiedName Public ReadOnly Property TupleType As Integer = SyntaxKind.TupleType Implements ISyntaxKinds.TupleType Public ReadOnly Property CharacterLiteralExpression As Integer = SyntaxKind.CharacterLiteralExpression Implements ISyntaxKinds.CharacterLiteralExpression Public ReadOnly Property DefaultLiteralExpression As Integer = SyntaxKind.NothingLiteralExpression Implements ISyntaxKinds.DefaultLiteralExpression Public ReadOnly Property FalseLiteralExpression As Integer = SyntaxKind.FalseLiteralExpression Implements ISyntaxKinds.FalseLiteralExpression Public ReadOnly Property NullLiteralExpression As Integer = SyntaxKind.NothingLiteralExpression Implements ISyntaxKinds.NullLiteralExpression Public ReadOnly Property StringLiteralExpression As Integer = SyntaxKind.StringLiteralExpression Implements ISyntaxKinds.StringLiteralExpression Public ReadOnly Property TrueLiteralExpression As Integer = SyntaxKind.TrueLiteralExpression Implements ISyntaxKinds.TrueLiteralExpression Public ReadOnly Property AnonymousObjectCreationExpression As Integer = SyntaxKind.AnonymousObjectCreationExpression Implements ISyntaxKinds.AnonymousObjectCreationExpression Public ReadOnly Property AwaitExpression As Integer = SyntaxKind.AwaitExpression Implements ISyntaxKinds.AwaitExpression Public ReadOnly Property BaseExpression As Integer = SyntaxKind.MyBaseExpression Implements ISyntaxKinds.BaseExpression Public ReadOnly Property ConditionalAccessExpression As Integer = SyntaxKind.ConditionalAccessExpression Implements ISyntaxKinds.ConditionalAccessExpression Public ReadOnly Property ConditionalExpression As Integer = SyntaxKind.TernaryConditionalExpression Implements ISyntaxKinds.ConditionalExpression Public ReadOnly Property InvocationExpression As Integer = SyntaxKind.InvocationExpression Implements ISyntaxKinds.InvocationExpression Public ReadOnly Property LogicalAndExpression As Integer = SyntaxKind.AndAlsoExpression Implements ISyntaxKinds.LogicalAndExpression Public ReadOnly Property LogicalOrExpression As Integer = SyntaxKind.OrElseExpression Implements ISyntaxKinds.LogicalOrExpression Public ReadOnly Property LogicalNotExpression As Integer = SyntaxKind.NotExpression Implements ISyntaxKinds.LogicalNotExpression Public ReadOnly Property ObjectCreationExpression As Integer = SyntaxKind.ObjectCreationExpression Implements ISyntaxKinds.ObjectCreationExpression Public ReadOnly Property ParenthesizedExpression As Integer = SyntaxKind.ParenthesizedExpression Implements ISyntaxKinds.ParenthesizedExpression Public ReadOnly Property QueryExpression As Integer = SyntaxKind.QueryExpression Implements ISyntaxKinds.QueryExpression Public ReadOnly Property ReferenceEqualsExpression As Integer = SyntaxKind.IsExpression Implements ISyntaxKinds.ReferenceEqualsExpression Public ReadOnly Property ReferenceNotEqualsExpression As Integer = SyntaxKind.IsNotExpression Implements ISyntaxKinds.ReferenceNotEqualsExpression Public ReadOnly Property SimpleMemberAccessExpression As Integer = SyntaxKind.SimpleMemberAccessExpression Implements ISyntaxKinds.SimpleMemberAccessExpression Public ReadOnly Property TernaryConditionalExpression As Integer = SyntaxKind.TernaryConditionalExpression Implements ISyntaxKinds.TernaryConditionalExpression Public ReadOnly Property ThisExpression As Integer = SyntaxKind.MeExpression Implements ISyntaxKinds.ThisExpression Public ReadOnly Property TupleExpression As Integer = SyntaxKind.TupleExpression Implements ISyntaxKinds.TupleExpression Public ReadOnly Property EndOfFileToken As Integer = SyntaxKind.EndOfFileToken Implements ISyntaxKinds.EndOfFileToken Public ReadOnly Property AwaitKeyword As Integer = SyntaxKind.AwaitKeyword Implements ISyntaxKinds.AwaitKeyword Public ReadOnly Property IdentifierToken As Integer = SyntaxKind.IdentifierToken Implements ISyntaxKinds.IdentifierToken Public ReadOnly Property GlobalKeyword As Integer = SyntaxKind.GlobalKeyword Implements ISyntaxKinds.GlobalKeyword Public ReadOnly Property IncompleteMember As Integer = SyntaxKind.IncompleteMember Implements ISyntaxKinds.IncompleteMember Public ReadOnly Property HashToken As Integer = SyntaxKind.HashToken Implements ISyntaxKinds.HashToken Public ReadOnly Property ExpressionStatement As Integer = SyntaxKind.ExpressionStatement Implements ISyntaxKinds.ExpressionStatement Public ReadOnly Property ForEachStatement As Integer = SyntaxKind.ForEachStatement Implements ISyntaxKinds.ForEachStatement Public ReadOnly Property LocalDeclarationStatement As Integer = SyntaxKind.LocalDeclarationStatement Implements ISyntaxKinds.LocalDeclarationStatement Public ReadOnly Property LockStatement As Integer = SyntaxKind.SyncLockStatement Implements ISyntaxKinds.LockStatement Public ReadOnly Property ReturnStatement As Integer = SyntaxKind.ReturnStatement Implements ISyntaxKinds.ReturnStatement Public ReadOnly Property UsingStatement As Integer = SyntaxKind.UsingStatement Implements ISyntaxKinds.UsingStatement Public ReadOnly Property Attribute As Integer = SyntaxKind.Attribute Implements ISyntaxKinds.Attribute Public ReadOnly Property Parameter As Integer = SyntaxKind.Parameter Implements ISyntaxKinds.Parameter Public ReadOnly Property TypeConstraint As Integer = SyntaxKind.TypeConstraint Implements ISyntaxKinds.TypeConstraint Public ReadOnly Property VariableDeclarator As Integer = SyntaxKind.VariableDeclarator Implements ISyntaxKinds.VariableDeclarator Public ReadOnly Property FieldDeclaration As Integer = SyntaxKind.FieldDeclaration Implements ISyntaxKinds.FieldDeclaration Public ReadOnly Property ParameterList As Integer = SyntaxKind.ParameterList Implements ISyntaxKinds.ParameterList Public ReadOnly Property TypeArgumentList As Integer = SyntaxKind.TypeArgumentList Implements ISyntaxKinds.TypeArgumentList Public ReadOnly Property GlobalStatement As Integer? Implements ISyntaxKinds.GlobalStatement Public ReadOnly Property EqualsValueClause As Integer = SyntaxKind.EqualsValue Implements ISyntaxKinds.EqualsValueClause Public ReadOnly Property Interpolation As Integer = SyntaxKind.Interpolation Implements ISyntaxKinds.Interpolation Public ReadOnly Property InterpolatedStringExpression As Integer = SyntaxKind.InterpolatedStringExpression Implements ISyntaxKinds.InterpolatedStringExpression Public ReadOnly Property InterpolatedStringText As Integer = SyntaxKind.InterpolatedStringText Implements ISyntaxKinds.InterpolatedStringText 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.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices Friend Class VisualBasicSyntaxKinds Implements ISyntaxKinds Public Shared ReadOnly Instance As New VisualBasicSyntaxKinds() Protected Sub New() End Sub Public Function Convert(Of TSyntaxKind As Structure)(kind As Integer) As TSyntaxKind Implements ISyntaxKinds.Convert ' Boxing/Unboxing casts from Object to TSyntaxKind will be erased by jit. Return CType(CType(CType(kind, SyntaxKind), Object), TSyntaxKind) End Function Public ReadOnly Property ConflictMarkerTrivia As Integer = SyntaxKind.ConflictMarkerTrivia Implements ISyntaxKinds.ConflictMarkerTrivia Public ReadOnly Property DisabledTextTrivia As Integer = SyntaxKind.DisabledTextTrivia Implements ISyntaxKinds.DisabledTextTrivia Public ReadOnly Property EndOfLineTrivia As Integer = SyntaxKind.EndOfLineTrivia Implements ISyntaxKinds.EndOfLineTrivia Public ReadOnly Property SkippedTokensTrivia As Integer = SyntaxKind.SkippedTokensTrivia Implements ISyntaxKinds.SkippedTokensTrivia Public ReadOnly Property WhitespaceTrivia As Integer = SyntaxKind.WhitespaceTrivia Implements ISyntaxKinds.WhitespaceTrivia Public ReadOnly Property SingleLineCommentTrivia As Integer = SyntaxKind.CommentTrivia Implements ISyntaxKinds.SingleLineCommentTrivia Private ReadOnly Property MultiLineCommentTrivia As Integer? Implements ISyntaxKinds.MultiLineCommentTrivia Public ReadOnly Property CloseBraceToken As Integer = SyntaxKind.CloseBraceToken Implements ISyntaxKinds.CloseBraceToken Public ReadOnly Property ColonToken As Integer = SyntaxKind.ColonToken Implements ISyntaxKinds.ColonToken Public ReadOnly Property CharacterLiteralToken As Integer = SyntaxKind.CharacterLiteralToken Implements ISyntaxKinds.CharacterLiteralToken Public ReadOnly Property DotToken As Integer = SyntaxKind.DotToken Implements ISyntaxKinds.DotToken Public ReadOnly Property InterpolatedStringTextToken As Integer = SyntaxKind.InterpolatedStringTextToken Implements ISyntaxKinds.InterpolatedStringTextToken Public ReadOnly Property QuestionToken As Integer = SyntaxKind.QuestionToken Implements ISyntaxKinds.QuestionToken Public ReadOnly Property StringLiteralToken As Integer = SyntaxKind.StringLiteralToken Implements ISyntaxKinds.StringLiteralToken Public ReadOnly Property IfKeyword As Integer = SyntaxKind.IfKeyword Implements ISyntaxKinds.IfKeyword Public ReadOnly Property GenericName As Integer = SyntaxKind.GenericName Implements ISyntaxKinds.GenericName Public ReadOnly Property IdentifierName As Integer = SyntaxKind.IdentifierName Implements ISyntaxKinds.IdentifierName Public ReadOnly Property QualifiedName As Integer = SyntaxKind.QualifiedName Implements ISyntaxKinds.QualifiedName Public ReadOnly Property TupleType As Integer = SyntaxKind.TupleType Implements ISyntaxKinds.TupleType Public ReadOnly Property CharacterLiteralExpression As Integer = SyntaxKind.CharacterLiteralExpression Implements ISyntaxKinds.CharacterLiteralExpression Public ReadOnly Property DefaultLiteralExpression As Integer = SyntaxKind.NothingLiteralExpression Implements ISyntaxKinds.DefaultLiteralExpression Public ReadOnly Property FalseLiteralExpression As Integer = SyntaxKind.FalseLiteralExpression Implements ISyntaxKinds.FalseLiteralExpression Public ReadOnly Property NullLiteralExpression As Integer = SyntaxKind.NothingLiteralExpression Implements ISyntaxKinds.NullLiteralExpression Public ReadOnly Property StringLiteralExpression As Integer = SyntaxKind.StringLiteralExpression Implements ISyntaxKinds.StringLiteralExpression Public ReadOnly Property TrueLiteralExpression As Integer = SyntaxKind.TrueLiteralExpression Implements ISyntaxKinds.TrueLiteralExpression Public ReadOnly Property AnonymousObjectCreationExpression As Integer = SyntaxKind.AnonymousObjectCreationExpression Implements ISyntaxKinds.AnonymousObjectCreationExpression Public ReadOnly Property AwaitExpression As Integer = SyntaxKind.AwaitExpression Implements ISyntaxKinds.AwaitExpression Public ReadOnly Property BaseExpression As Integer = SyntaxKind.MyBaseExpression Implements ISyntaxKinds.BaseExpression Public ReadOnly Property ConditionalAccessExpression As Integer = SyntaxKind.ConditionalAccessExpression Implements ISyntaxKinds.ConditionalAccessExpression Public ReadOnly Property ConditionalExpression As Integer = SyntaxKind.TernaryConditionalExpression Implements ISyntaxKinds.ConditionalExpression Public ReadOnly Property InvocationExpression As Integer = SyntaxKind.InvocationExpression Implements ISyntaxKinds.InvocationExpression Public ReadOnly Property LogicalAndExpression As Integer = SyntaxKind.AndAlsoExpression Implements ISyntaxKinds.LogicalAndExpression Public ReadOnly Property LogicalOrExpression As Integer = SyntaxKind.OrElseExpression Implements ISyntaxKinds.LogicalOrExpression Public ReadOnly Property LogicalNotExpression As Integer = SyntaxKind.NotExpression Implements ISyntaxKinds.LogicalNotExpression Public ReadOnly Property ObjectCreationExpression As Integer = SyntaxKind.ObjectCreationExpression Implements ISyntaxKinds.ObjectCreationExpression Public ReadOnly Property ParenthesizedExpression As Integer = SyntaxKind.ParenthesizedExpression Implements ISyntaxKinds.ParenthesizedExpression Public ReadOnly Property QueryExpression As Integer = SyntaxKind.QueryExpression Implements ISyntaxKinds.QueryExpression Public ReadOnly Property ReferenceEqualsExpression As Integer = SyntaxKind.IsExpression Implements ISyntaxKinds.ReferenceEqualsExpression Public ReadOnly Property ReferenceNotEqualsExpression As Integer = SyntaxKind.IsNotExpression Implements ISyntaxKinds.ReferenceNotEqualsExpression Public ReadOnly Property SimpleMemberAccessExpression As Integer = SyntaxKind.SimpleMemberAccessExpression Implements ISyntaxKinds.SimpleMemberAccessExpression Public ReadOnly Property TernaryConditionalExpression As Integer = SyntaxKind.TernaryConditionalExpression Implements ISyntaxKinds.TernaryConditionalExpression Public ReadOnly Property ThisExpression As Integer = SyntaxKind.MeExpression Implements ISyntaxKinds.ThisExpression Public ReadOnly Property TupleExpression As Integer = SyntaxKind.TupleExpression Implements ISyntaxKinds.TupleExpression Public ReadOnly Property EndOfFileToken As Integer = SyntaxKind.EndOfFileToken Implements ISyntaxKinds.EndOfFileToken Public ReadOnly Property AwaitKeyword As Integer = SyntaxKind.AwaitKeyword Implements ISyntaxKinds.AwaitKeyword Public ReadOnly Property IdentifierToken As Integer = SyntaxKind.IdentifierToken Implements ISyntaxKinds.IdentifierToken Public ReadOnly Property GlobalKeyword As Integer = SyntaxKind.GlobalKeyword Implements ISyntaxKinds.GlobalKeyword Public ReadOnly Property IncompleteMember As Integer = SyntaxKind.IncompleteMember Implements ISyntaxKinds.IncompleteMember Public ReadOnly Property HashToken As Integer = SyntaxKind.HashToken Implements ISyntaxKinds.HashToken Public ReadOnly Property ExpressionStatement As Integer = SyntaxKind.ExpressionStatement Implements ISyntaxKinds.ExpressionStatement Public ReadOnly Property ForEachStatement As Integer = SyntaxKind.ForEachStatement Implements ISyntaxKinds.ForEachStatement Public ReadOnly Property LocalDeclarationStatement As Integer = SyntaxKind.LocalDeclarationStatement Implements ISyntaxKinds.LocalDeclarationStatement Public ReadOnly Property LockStatement As Integer = SyntaxKind.SyncLockStatement Implements ISyntaxKinds.LockStatement Public ReadOnly Property ReturnStatement As Integer = SyntaxKind.ReturnStatement Implements ISyntaxKinds.ReturnStatement Public ReadOnly Property UsingStatement As Integer = SyntaxKind.UsingStatement Implements ISyntaxKinds.UsingStatement Public ReadOnly Property Attribute As Integer = SyntaxKind.Attribute Implements ISyntaxKinds.Attribute Public ReadOnly Property Parameter As Integer = SyntaxKind.Parameter Implements ISyntaxKinds.Parameter Public ReadOnly Property TypeConstraint As Integer = SyntaxKind.TypeConstraint Implements ISyntaxKinds.TypeConstraint Public ReadOnly Property VariableDeclarator As Integer = SyntaxKind.VariableDeclarator Implements ISyntaxKinds.VariableDeclarator Public ReadOnly Property FieldDeclaration As Integer = SyntaxKind.FieldDeclaration Implements ISyntaxKinds.FieldDeclaration Public ReadOnly Property ParameterList As Integer = SyntaxKind.ParameterList Implements ISyntaxKinds.ParameterList Public ReadOnly Property TypeArgumentList As Integer = SyntaxKind.TypeArgumentList Implements ISyntaxKinds.TypeArgumentList Public ReadOnly Property GlobalStatement As Integer? Implements ISyntaxKinds.GlobalStatement Public ReadOnly Property EqualsValueClause As Integer = SyntaxKind.EqualsValue Implements ISyntaxKinds.EqualsValueClause Public ReadOnly Property Interpolation As Integer = SyntaxKind.Interpolation Implements ISyntaxKinds.Interpolation Public ReadOnly Property InterpolatedStringExpression As Integer = SyntaxKind.InterpolatedStringExpression Implements ISyntaxKinds.InterpolatedStringExpression Public ReadOnly Property InterpolatedStringText As Integer = SyntaxKind.InterpolatedStringText Implements ISyntaxKinds.InterpolatedStringText End Class End Namespace
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Features/VisualBasic/Portable/Wrapping/ChainedExpression/VisualBasicChainedExpressionWrapper.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Indentation Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Wrapping.ChainedExpression Namespace Microsoft.CodeAnalysis.VisualBasic.Wrapping.ChainedExpression Friend Class VisualBasicChainedExpressionWrapper Inherits AbstractChainedExpressionWrapper(Of NameSyntax, ArgumentListSyntax) Public Sub New() MyBase.New(VisualBasicIndentationService.WithoutParameterAlignmentInstance, VisualBasicSyntaxFacts.Instance) End Sub Protected Overrides Function GetNewLineBeforeOperatorTrivia(newLine As SyntaxTriviaList) As SyntaxTriviaList Return newLine.InsertRange(0, {SyntaxFactory.WhitespaceTrivia(" "), SyntaxFactory.LineContinuationTrivia("_")}) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Indentation Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Wrapping.ChainedExpression Namespace Microsoft.CodeAnalysis.VisualBasic.Wrapping.ChainedExpression Friend Class VisualBasicChainedExpressionWrapper Inherits AbstractChainedExpressionWrapper(Of NameSyntax, ArgumentListSyntax) Public Sub New() MyBase.New(VisualBasicIndentationService.WithoutParameterAlignmentInstance, VisualBasicSyntaxFacts.Instance) End Sub Protected Overrides Function GetNewLineBeforeOperatorTrivia(newLine As SyntaxTriviaList) As SyntaxTriviaList Return newLine.InsertRange(0, {SyntaxFactory.WhitespaceTrivia(" "), SyntaxFactory.LineContinuationTrivia("_")}) End Function End Class End Namespace
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicInstructionDecoder.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.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.VisualStudio.Debugger Imports Microsoft.VisualStudio.Debugger.Clr Imports System.Text Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class VisualBasicInstructionDecoder : Inherits InstructionDecoder(Of VisualBasicCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol) ' These strings were not localized in the old EE. We'll keep them that way ' so as not to break consumers who may have been parsing frame names... Private Const s_closureDisplayName As String = "<closure>" Private Const s_lambdaDisplayName As String = "<lambda{0}>" ''' <summary> ''' Singleton instance of <see cref="VisualBasicInstructionDecoder"/> (created using default constructor). ''' </summary> Friend Shared ReadOnly Instance As VisualBasicInstructionDecoder = New VisualBasicInstructionDecoder() Private Sub New() End Sub Friend Overrides Sub AppendFullName(builder As StringBuilder, method As MethodSymbol) Dim parts = method.ToDisplayParts(DisplayFormat) Dim numParts = parts.Length For i = 0 To numParts - 1 Dim part = parts(i) Dim displayString = part.ToString() Select Case part.Kind Case SymbolDisplayPartKind.ClassName If Not displayString.StartsWith(StringConstants.DisplayClassPrefix, StringComparison.Ordinal) Then builder.Append(displayString) Else ' Drop any remaining display class name parts and the subsequent dot... Do i += 1 Loop While ((i < numParts) AndAlso parts(i).Kind <> SymbolDisplayPartKind.MethodName) i -= 1 End If Case SymbolDisplayPartKind.MethodName If displayString.StartsWith(StringConstants.LambdaMethodNamePrefix, StringComparison.Ordinal) Then builder.Append(s_closureDisplayName) builder.Append("."c) ' NOTE: The old implementation only appended the first ordinal number. Since this is not useful ' in uniquely identifying the lambda, we'll append the entire ordinal suffix (which may contain ' multiple numbers, as well as '-' or '_'). builder.AppendFormat(s_lambdaDisplayName, displayString.Substring(StringConstants.LambdaMethodNamePrefix.Length)) Else builder.Append(displayString) End If Case SymbolDisplayPartKind.PropertyName builder.Append(method.Name) Case Else builder.Append(displayString) End Select Next End Sub Friend Overrides Function ConstructMethod(method As MethodSymbol, typeParameters As ImmutableArray(Of TypeParameterSymbol), typeArguments As ImmutableArray(Of TypeSymbol)) As MethodSymbol Dim methodArity = method.Arity Dim methodArgumentStartIndex = typeParameters.Length - methodArity Dim typeMap = TypeSubstitution.Create( method, ImmutableArray.Create(typeParameters, 0, methodArgumentStartIndex), ImmutableArray.Create(typeArguments, 0, methodArgumentStartIndex)) Dim substitutedType = typeMap.SubstituteNamedType(method.ContainingType) method = method.AsMember(substitutedType) If methodArity > 0 Then method = method.Construct(ImmutableArray.Create(typeArguments, methodArgumentStartIndex, methodArity)) End If Return method End Function Friend Overrides Function GetAllTypeParameters(method As MethodSymbol) As ImmutableArray(Of TypeParameterSymbol) Return method.GetAllTypeParameters() End Function Friend Overrides Function GetCompilation(moduleInstance As DkmClrModuleInstance) As VisualBasicCompilation Dim appDomain = moduleInstance.AppDomain Dim moduleVersionId = moduleInstance.Mvid Dim previous = appDomain.GetMetadataContext(Of VisualBasicMetadataContext)() Dim metadataBlocks = moduleInstance.RuntimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks) Dim kind = GetMakeAssemblyReferencesKind() Dim contextId = MetadataContextId.GetContextId(moduleVersionId, kind) Dim assemblyContexts = If(previous.Matches(metadataBlocks), previous.AssemblyContexts, ImmutableDictionary(Of MetadataContextId, VisualBasicMetadataContext).Empty) Dim previousContext As VisualBasicMetadataContext = Nothing assemblyContexts.TryGetValue(contextId, previousContext) Dim compilation = previousContext.Compilation If compilation Is Nothing Then compilation = metadataBlocks.ToCompilation(moduleVersionId, kind) appDomain.SetMetadataContext( New MetadataContext(Of VisualBasicMetadataContext)( metadataBlocks, assemblyContexts.SetItem(contextId, New VisualBasicMetadataContext(compilation))), report:=kind = MakeAssemblyReferencesKind.AllReferences) End If Return compilation End Function Friend Overrides Function GetMethod(compilation As VisualBasicCompilation, instructionAddress As DkmClrInstructionAddress) As MethodSymbol Dim methodHandle = CType(MetadataTokens.Handle(instructionAddress.MethodId.Token), MethodDefinitionHandle) Return compilation.GetSourceMethod(instructionAddress.ModuleInstance.Mvid, methodHandle) End Function Friend Overrides Function GetTypeNameDecoder(compilation As VisualBasicCompilation, method As MethodSymbol) As TypeNameDecoder(Of PEModuleSymbol, TypeSymbol) Debug.Assert(TypeOf method Is PEMethodSymbol) Return New EETypeNameDecoder(compilation, DirectCast(method.ContainingModule, PEModuleSymbol)) 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.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.VisualStudio.Debugger Imports Microsoft.VisualStudio.Debugger.Clr Imports System.Text Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class VisualBasicInstructionDecoder : Inherits InstructionDecoder(Of VisualBasicCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol) ' These strings were not localized in the old EE. We'll keep them that way ' so as not to break consumers who may have been parsing frame names... Private Const s_closureDisplayName As String = "<closure>" Private Const s_lambdaDisplayName As String = "<lambda{0}>" ''' <summary> ''' Singleton instance of <see cref="VisualBasicInstructionDecoder"/> (created using default constructor). ''' </summary> Friend Shared ReadOnly Instance As VisualBasicInstructionDecoder = New VisualBasicInstructionDecoder() Private Sub New() End Sub Friend Overrides Sub AppendFullName(builder As StringBuilder, method As MethodSymbol) Dim parts = method.ToDisplayParts(DisplayFormat) Dim numParts = parts.Length For i = 0 To numParts - 1 Dim part = parts(i) Dim displayString = part.ToString() Select Case part.Kind Case SymbolDisplayPartKind.ClassName If Not displayString.StartsWith(StringConstants.DisplayClassPrefix, StringComparison.Ordinal) Then builder.Append(displayString) Else ' Drop any remaining display class name parts and the subsequent dot... Do i += 1 Loop While ((i < numParts) AndAlso parts(i).Kind <> SymbolDisplayPartKind.MethodName) i -= 1 End If Case SymbolDisplayPartKind.MethodName If displayString.StartsWith(StringConstants.LambdaMethodNamePrefix, StringComparison.Ordinal) Then builder.Append(s_closureDisplayName) builder.Append("."c) ' NOTE: The old implementation only appended the first ordinal number. Since this is not useful ' in uniquely identifying the lambda, we'll append the entire ordinal suffix (which may contain ' multiple numbers, as well as '-' or '_'). builder.AppendFormat(s_lambdaDisplayName, displayString.Substring(StringConstants.LambdaMethodNamePrefix.Length)) Else builder.Append(displayString) End If Case SymbolDisplayPartKind.PropertyName builder.Append(method.Name) Case Else builder.Append(displayString) End Select Next End Sub Friend Overrides Function ConstructMethod(method As MethodSymbol, typeParameters As ImmutableArray(Of TypeParameterSymbol), typeArguments As ImmutableArray(Of TypeSymbol)) As MethodSymbol Dim methodArity = method.Arity Dim methodArgumentStartIndex = typeParameters.Length - methodArity Dim typeMap = TypeSubstitution.Create( method, ImmutableArray.Create(typeParameters, 0, methodArgumentStartIndex), ImmutableArray.Create(typeArguments, 0, methodArgumentStartIndex)) Dim substitutedType = typeMap.SubstituteNamedType(method.ContainingType) method = method.AsMember(substitutedType) If methodArity > 0 Then method = method.Construct(ImmutableArray.Create(typeArguments, methodArgumentStartIndex, methodArity)) End If Return method End Function Friend Overrides Function GetAllTypeParameters(method As MethodSymbol) As ImmutableArray(Of TypeParameterSymbol) Return method.GetAllTypeParameters() End Function Friend Overrides Function GetCompilation(moduleInstance As DkmClrModuleInstance) As VisualBasicCompilation Dim appDomain = moduleInstance.AppDomain Dim moduleVersionId = moduleInstance.Mvid Dim previous = appDomain.GetMetadataContext(Of VisualBasicMetadataContext)() Dim metadataBlocks = moduleInstance.RuntimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks) Dim kind = GetMakeAssemblyReferencesKind() Dim contextId = MetadataContextId.GetContextId(moduleVersionId, kind) Dim assemblyContexts = If(previous.Matches(metadataBlocks), previous.AssemblyContexts, ImmutableDictionary(Of MetadataContextId, VisualBasicMetadataContext).Empty) Dim previousContext As VisualBasicMetadataContext = Nothing assemblyContexts.TryGetValue(contextId, previousContext) Dim compilation = previousContext.Compilation If compilation Is Nothing Then compilation = metadataBlocks.ToCompilation(moduleVersionId, kind) appDomain.SetMetadataContext( New MetadataContext(Of VisualBasicMetadataContext)( metadataBlocks, assemblyContexts.SetItem(contextId, New VisualBasicMetadataContext(compilation))), report:=kind = MakeAssemblyReferencesKind.AllReferences) End If Return compilation End Function Friend Overrides Function GetMethod(compilation As VisualBasicCompilation, instructionAddress As DkmClrInstructionAddress) As MethodSymbol Dim methodHandle = CType(MetadataTokens.Handle(instructionAddress.MethodId.Token), MethodDefinitionHandle) Return compilation.GetSourceMethod(instructionAddress.ModuleInstance.Mvid, methodHandle) End Function Friend Overrides Function GetTypeNameDecoder(compilation As VisualBasicCompilation, method As MethodSymbol) As TypeNameDecoder(Of PEModuleSymbol, TypeSymbol) Debug.Assert(TypeOf method Is PEMethodSymbol) Return New EETypeNameDecoder(compilation, DirectCast(method.ContainingModule, PEModuleSymbol)) End Function End Class End Namespace
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/VisualStudio/Core/Def/Implementation/CommonControls/NewTypeDestinationSelectionViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls { internal class NewTypeDestinationSelectionViewModel : AbstractNotifyPropertyChanged { public static NewTypeDestinationSelectionViewModel Default = new( string.Empty, LanguageNames.CSharp, string.Empty, string.Empty, ImmutableArray<string>.Empty, null ); private readonly string _fileExtension; private readonly string _defaultNamespace; private readonly string _generatedNameTypeParameterSuffix; private readonly ImmutableArray<string> _conflictingNames; private readonly string _defaultName; private readonly ISyntaxFactsService? _syntaxFactsService; private readonly string _languageName; public NewTypeDestinationSelectionViewModel( string defaultName, string languageName, string defaultNamespace, string generatedNameTypeParameterSuffix, ImmutableArray<string> conflictingNames, ISyntaxFactsService? syntaxFactsService) { _defaultName = defaultName; _fileExtension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; _languageName = languageName; _generatedNameTypeParameterSuffix = generatedNameTypeParameterSuffix; _conflictingNames = conflictingNames; _defaultNamespace = defaultNamespace; _typeName = _defaultName; _syntaxFactsService = syntaxFactsService; _fileName = $"{defaultName}{_fileExtension}"; } private string _typeName; public string TypeName { get { return _typeName; } set { if (SetProperty(ref _typeName, value)) { FileName = string.Format("{0}{1}", value.Trim(), _fileExtension); NotifyPropertyChanged(nameof(GeneratedName)); } } } public string GeneratedName { get { return string.Format( "{0}{1}{2}", string.IsNullOrEmpty(_defaultNamespace) ? string.Empty : _defaultNamespace + ".", _typeName.Trim(), _generatedNameTypeParameterSuffix); } } private string _fileName; public string FileName { get { return _fileName; } set { SetProperty(ref _fileName, value); } } private NewTypeDestination _destination = NewTypeDestination.NewFile; public NewTypeDestination Destination { get { return _destination; } set { if (SetProperty(ref _destination, value)) { NotifyPropertyChanged(nameof(FileNameEnabled)); } } } internal bool TrySubmit([NotNullWhen(returnValue: false)] out string? message) { message = null; if (_syntaxFactsService is null) { throw new InvalidOperationException(); } var trimmedName = TypeName.Trim(); if (_conflictingNames.Contains(trimmedName)) { message = ServicesVSResources.Name_conflicts_with_an_existing_type_name; return false; } if (!_syntaxFactsService.IsValidIdentifier(trimmedName)) { message = string.Format(ServicesVSResources.Name_is_not_a_valid_0_identifier, _languageName); return false; } var trimmedFileName = FileName.Trim(); if (!Path.GetExtension(trimmedFileName).Equals(_fileExtension, StringComparison.OrdinalIgnoreCase)) { message = string.Format(ServicesVSResources.File_name_must_have_the_0_extension, _fileExtension); return false; } if (trimmedFileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { message = ServicesVSResources.Illegal_characters_in_path; return false; } return true; } public bool FileNameEnabled => Destination == NewTypeDestination.NewFile; } internal enum NewTypeDestination { CurrentFile, NewFile }; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls { internal class NewTypeDestinationSelectionViewModel : AbstractNotifyPropertyChanged { public static NewTypeDestinationSelectionViewModel Default = new( string.Empty, LanguageNames.CSharp, string.Empty, string.Empty, ImmutableArray<string>.Empty, null ); private readonly string _fileExtension; private readonly string _defaultNamespace; private readonly string _generatedNameTypeParameterSuffix; private readonly ImmutableArray<string> _conflictingNames; private readonly string _defaultName; private readonly ISyntaxFactsService? _syntaxFactsService; private readonly string _languageName; public NewTypeDestinationSelectionViewModel( string defaultName, string languageName, string defaultNamespace, string generatedNameTypeParameterSuffix, ImmutableArray<string> conflictingNames, ISyntaxFactsService? syntaxFactsService) { _defaultName = defaultName; _fileExtension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; _languageName = languageName; _generatedNameTypeParameterSuffix = generatedNameTypeParameterSuffix; _conflictingNames = conflictingNames; _defaultNamespace = defaultNamespace; _typeName = _defaultName; _syntaxFactsService = syntaxFactsService; _fileName = $"{defaultName}{_fileExtension}"; } private string _typeName; public string TypeName { get { return _typeName; } set { if (SetProperty(ref _typeName, value)) { FileName = string.Format("{0}{1}", value.Trim(), _fileExtension); NotifyPropertyChanged(nameof(GeneratedName)); } } } public string GeneratedName { get { return string.Format( "{0}{1}{2}", string.IsNullOrEmpty(_defaultNamespace) ? string.Empty : _defaultNamespace + ".", _typeName.Trim(), _generatedNameTypeParameterSuffix); } } private string _fileName; public string FileName { get { return _fileName; } set { SetProperty(ref _fileName, value); } } private NewTypeDestination _destination = NewTypeDestination.NewFile; public NewTypeDestination Destination { get { return _destination; } set { if (SetProperty(ref _destination, value)) { NotifyPropertyChanged(nameof(FileNameEnabled)); } } } internal bool TrySubmit([NotNullWhen(returnValue: false)] out string? message) { message = null; if (_syntaxFactsService is null) { throw new InvalidOperationException(); } var trimmedName = TypeName.Trim(); if (_conflictingNames.Contains(trimmedName)) { message = ServicesVSResources.Name_conflicts_with_an_existing_type_name; return false; } if (!_syntaxFactsService.IsValidIdentifier(trimmedName)) { message = string.Format(ServicesVSResources.Name_is_not_a_valid_0_identifier, _languageName); return false; } var trimmedFileName = FileName.Trim(); if (!Path.GetExtension(trimmedFileName).Equals(_fileExtension, StringComparison.OrdinalIgnoreCase)) { message = string.Format(ServicesVSResources.File_name_must_have_the_0_extension, _fileExtension); return false; } if (trimmedFileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { message = ServicesVSResources.Illegal_characters_in_path; return false; } return true; } public bool FileNameEnabled => Destination == NewTypeDestination.NewFile; } internal enum NewTypeDestination { CurrentFile, NewFile }; }
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Compilers/VisualBasic/Test/Syntax/Parser/ParseAsyncTests.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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Public Class ParseAsyncTests Inherits BasicTestBase <Fact> Public Sub ParseAsyncModifier() Dim tree = ParseAndVerify(<![CDATA[ Imports Async = System.Threading.Tasks.Task Module Program Public Const Async As Integer = 0 Public Async <Async(Async)> Async Function M() As Async Dim l = Sub() Dim async As Async = Nothing End Sub Dim l2 = Async Sub() Dim async As Async = Nothing End Sub End Function End Module Class AsyncAttribute Inherits Attribute Sub New(p) End Sub End Class]]>) Assert.Equal(2, Aggregate t In tree.GetRoot().DescendantTokens Where t.Kind = SyntaxKind.AsyncKeyword Into Count()) Dim fields = tree.GetRoot().DescendantNodes.OfType(Of FieldDeclarationSyntax)().ToArray() Assert.Equal(2, Aggregate f In fields Where f.Declarators(0).Names(0).Identifier.ValueText = "Async" Into Count()) End Sub <Fact> Public Sub ParseAwaitExpressions() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Console Module Program Private t1 As Task Private t2 As Task(Of Integer) Async Sub M() Await t1 WriteLine(Await t2) End Sub Sub M2() Await t1 WriteLine(Await t2) End Sub Async Function N() As Task(Of Integer) Await t1 Return Await t2 End Function Function N2() Await t1 Return (Await t2) End Function End Module]]>, <errors> <error id="30800" message="Method arguments must be enclosed in parentheses." start="206" end="208"/> <error id="32017" message="Comma, ')', or a valid expression continuation expected." start="234" end="236"/> <error id="30800" message="Method arguments must be enclosed in parentheses." start="398" end="400"/> <error id="30198" message="')' expected." start="424" end="424"/> </errors>) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax)() Assert.Equal(4, awaitExpressions.Count) Dim firstStatementOfM = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax).First.Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfM2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(1).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(2).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(3).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) End Sub <Fact> Public Sub ParseAwaitExpressionsWithPrecedence() Dim tree = ParseAndVerify(<![CDATA[ Module Program Async Function M(a As Task(Of Integer), x As Task(Of Integer), y As Task(Of Integer), b As Task(Of Integer)) As Task(Of Integer) Return Await a * Await x ^ Await y + Await b End Function End Module]]>) Dim returnStatement = tree.GetRoot().DescendantNodes.OfType(Of ReturnStatementSyntax).Single() Dim expression = CType(returnStatement.Expression, BinaryExpressionSyntax) Assert.Equal(SyntaxKind.AddExpression, expression.Kind) Assert.Equal(SyntaxKind.MultiplyExpression, expression.Left.Kind) Dim left = CType(expression.Left, BinaryExpressionSyntax) Assert.Equal(SyntaxKind.AwaitExpression, left.Left.Kind) Assert.Equal(SyntaxKind.ExponentiateExpression, left.Right.Kind) Dim right = expression.Right Assert.Equal(SyntaxKind.AwaitExpression, right.Kind) End Sub <Fact> Public Sub ParseAwaitStatements() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Console Module Program Private t1 As Task Private t2 As Task(Of Integer) Async Sub M() ' await 1 Await t1 End Sub Sub M2() ' await 2 Await t1 Dim lambda = Async Sub() If True Then Await t1 : Await t2 ' await 3 and 4 End Sub Async Function N() As Task(Of Integer) ' await 5 Await t1 ' await 6 Return Await t2 End Function Function N2() Await t1 Return (Await t2) End Function Async Function N3(a, x, y) As Task ' This is a parse error, end of statement expected after 'Await a' Await a * Await x * Await y End Function End Module]]>, <errors> <error id="30800" message="Method arguments must be enclosed in parentheses." start="177" end="179"/> <error id="30800" message="Method arguments must be enclosed in parentheses." start="407" end="409"/> <error id="30198" message="')' expected." start="433" end="433"/> <error id="30205" message="End of statement expected." start="588" end="589"/> </errors>) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax)().ToArray() Assert.Equal(6, awaitExpressions.Count) Dim firstStatementOfM = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax).First.Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfM2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(1).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(2).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(3).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) End Sub <Fact> Public Sub ParseAsyncLambdas() Dim tree = ParseAndVerify(<![CDATA[ Module Program Private t1 As Task Private t2 As Task(Of Integer) Private f As Integer Sub Main() ' Statement Dim slAsyncSub1 = Async Sub() Await t1 ' Assignment Dim slAsyncSub2 = Async Sub() f = Await t2 ' Expression Dim slAsyncFunction1 = Async Function() Await t2 ' Comparison Dim slAsyncFunction2 = Async Function() f = Await t2 Dim mlAsyncSub = Async Sub() Await t1 End Sub Dim mlAsyncFunction1 = Async Function() Await t1 End Function Dim mlAsyncFunction2 = Async Function() Await t1 Return Await t2 End Function End Sub End Module]]>) Dim lambdas = tree.GetRoot().DescendantNodes.OfType(Of LambdaExpressionSyntax)().ToArray() Assert.Equal(7, lambdas.Count) Assert.Equal(4, lambdas.Count(Function(l) SyntaxFacts.IsSingleLineLambdaExpression(l.Kind))) Assert.Equal(SyntaxKind.ExpressionStatement, CType(lambdas(0), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(0), SingleLineLambdaExpressionSyntax).Body, ExpressionStatementSyntax).Expression.Kind) Assert.Equal(SyntaxKind.SimpleAssignmentStatement, CType(lambdas(1), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(1), SingleLineLambdaExpressionSyntax).Body, AssignmentStatementSyntax).Right.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(lambdas(2), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.EqualsExpression, CType(lambdas(3), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(3), SingleLineLambdaExpressionSyntax).Body, BinaryExpressionSyntax).Right.Kind) Assert.Equal(3, lambdas.Count(Function(l) SyntaxFacts.IsMultiLineLambdaExpression(l.Kind))) End Sub <Fact> Public Sub ParseAsyncWithNesting() Dim tree = VisualBasicSyntaxTree.ParseText(<![CDATA[ Imports Async = System.Threading.Tasks.Task Class C Public Const Async As Integer = 0 <Async(Async)> Async Function M() As Async Dim t As Task Await (t) ' Yes Dim lambda1 = Function() Await (t) ' No Dim lambda1a = Sub() Await (t) ' No Dim lambda1b = Async Function() Await t ' Yes Dim lambda1c = Async Function() Await (Sub() Await (Function() Await (Function() (Function() Async Sub() Await t)())()) End Sub) ' Yes, No, No, Yes Return Await t ' Yes End Function [Await] t ' No End Function Sub Await(Optional p = Nothing) Dim t As Task Await (t) ' No Dim lambda1 = Async Function() Await (t) ' Yes Dim lambda1a = Async Sub() Await (t) ' Yes Dim lambda1b = Function() Await (t) ' No Dim lambda1c = Function() Await (Async Sub() Await (Async Function() Await (Async Function() (Function() Sub() Await t)())()) End Sub) ' No, Yes, Yes, No Return Await (t) ' No End Function Await t End Sub Function Await(t) Return Nothing End Function End Class Class AsyncAttribute Inherits Attribute Sub New(p) End Sub End Class]]>.Value) ' Error BC30800: Method arguments must be enclosed in parentheses. Assert.True(Aggregate d In tree.GetDiagnostics() Into All(d.Code = ERRID.ERR_ObsoleteArgumentsNeedParens)) Dim asyncExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax).ToArray() Assert.Equal(9, asyncExpressions.Count) Dim invocationExpression = tree.GetRoot().DescendantNodes.OfType(Of InvocationExpressionSyntax).ToArray() Assert.Equal(9, asyncExpressions.Count) Dim allParsedExpressions = tree.GetRoot().DescendantNodes.OfType(Of ExpressionSyntax)() Dim parsedExpressions = From expression In allParsedExpressions Where expression.Kind = SyntaxKind.AwaitExpression OrElse (expression.Kind = SyntaxKind.IdentifierName AndAlso DirectCast(expression, IdentifierNameSyntax).Identifier.ValueText.Equals("Await")) Order By expression.Position Select expression.Kind Dim expected = {SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName} Assert.Equal(expected, parsedExpressions) End Sub <Fact> Public Sub ParseAwaitInScriptingAndInteractive() Dim source = " Dim i = Await T + Await(T) ' Yes, Yes Dim l = Sub() Await T ' No End Sub Function M() Return Await T ' No End Function Async Sub N() Await T ' Yes Await(T) ' Yes End Sub Async Function F() Return Await(T) ' Yes End Function" Dim tree = VisualBasicSyntaxTree.ParseText(source, options:=TestOptions.Script) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax).ToArray() Assert.Equal(5, awaitExpressions.Count) Dim awaitParsedAsIdentifier = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax).Where(Function(id) id.Identifier.ValueText.Equals("Await")).ToArray() Assert.Equal(2, awaitParsedAsIdentifier.Count) End Sub End Class
' Licensed to the .NET Foundation under one or more 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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Public Class ParseAsyncTests Inherits BasicTestBase <Fact> Public Sub ParseAsyncModifier() Dim tree = ParseAndVerify(<![CDATA[ Imports Async = System.Threading.Tasks.Task Module Program Public Const Async As Integer = 0 Public Async <Async(Async)> Async Function M() As Async Dim l = Sub() Dim async As Async = Nothing End Sub Dim l2 = Async Sub() Dim async As Async = Nothing End Sub End Function End Module Class AsyncAttribute Inherits Attribute Sub New(p) End Sub End Class]]>) Assert.Equal(2, Aggregate t In tree.GetRoot().DescendantTokens Where t.Kind = SyntaxKind.AsyncKeyword Into Count()) Dim fields = tree.GetRoot().DescendantNodes.OfType(Of FieldDeclarationSyntax)().ToArray() Assert.Equal(2, Aggregate f In fields Where f.Declarators(0).Names(0).Identifier.ValueText = "Async" Into Count()) End Sub <Fact> Public Sub ParseAwaitExpressions() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Console Module Program Private t1 As Task Private t2 As Task(Of Integer) Async Sub M() Await t1 WriteLine(Await t2) End Sub Sub M2() Await t1 WriteLine(Await t2) End Sub Async Function N() As Task(Of Integer) Await t1 Return Await t2 End Function Function N2() Await t1 Return (Await t2) End Function End Module]]>, <errors> <error id="30800" message="Method arguments must be enclosed in parentheses." start="206" end="208"/> <error id="32017" message="Comma, ')', or a valid expression continuation expected." start="234" end="236"/> <error id="30800" message="Method arguments must be enclosed in parentheses." start="398" end="400"/> <error id="30198" message="')' expected." start="424" end="424"/> </errors>) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax)() Assert.Equal(4, awaitExpressions.Count) Dim firstStatementOfM = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax).First.Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfM2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(1).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(2).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(3).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) End Sub <Fact> Public Sub ParseAwaitExpressionsWithPrecedence() Dim tree = ParseAndVerify(<![CDATA[ Module Program Async Function M(a As Task(Of Integer), x As Task(Of Integer), y As Task(Of Integer), b As Task(Of Integer)) As Task(Of Integer) Return Await a * Await x ^ Await y + Await b End Function End Module]]>) Dim returnStatement = tree.GetRoot().DescendantNodes.OfType(Of ReturnStatementSyntax).Single() Dim expression = CType(returnStatement.Expression, BinaryExpressionSyntax) Assert.Equal(SyntaxKind.AddExpression, expression.Kind) Assert.Equal(SyntaxKind.MultiplyExpression, expression.Left.Kind) Dim left = CType(expression.Left, BinaryExpressionSyntax) Assert.Equal(SyntaxKind.AwaitExpression, left.Left.Kind) Assert.Equal(SyntaxKind.ExponentiateExpression, left.Right.Kind) Dim right = expression.Right Assert.Equal(SyntaxKind.AwaitExpression, right.Kind) End Sub <Fact> Public Sub ParseAwaitStatements() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Console Module Program Private t1 As Task Private t2 As Task(Of Integer) Async Sub M() ' await 1 Await t1 End Sub Sub M2() ' await 2 Await t1 Dim lambda = Async Sub() If True Then Await t1 : Await t2 ' await 3 and 4 End Sub Async Function N() As Task(Of Integer) ' await 5 Await t1 ' await 6 Return Await t2 End Function Function N2() Await t1 Return (Await t2) End Function Async Function N3(a, x, y) As Task ' This is a parse error, end of statement expected after 'Await a' Await a * Await x * Await y End Function End Module]]>, <errors> <error id="30800" message="Method arguments must be enclosed in parentheses." start="177" end="179"/> <error id="30800" message="Method arguments must be enclosed in parentheses." start="407" end="409"/> <error id="30198" message="')' expected." start="433" end="433"/> <error id="30205" message="End of statement expected." start="588" end="589"/> </errors>) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax)().ToArray() Assert.Equal(6, awaitExpressions.Count) Dim firstStatementOfM = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax).First.Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfM2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(1).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(2).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(3).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) End Sub <Fact> Public Sub ParseAsyncLambdas() Dim tree = ParseAndVerify(<![CDATA[ Module Program Private t1 As Task Private t2 As Task(Of Integer) Private f As Integer Sub Main() ' Statement Dim slAsyncSub1 = Async Sub() Await t1 ' Assignment Dim slAsyncSub2 = Async Sub() f = Await t2 ' Expression Dim slAsyncFunction1 = Async Function() Await t2 ' Comparison Dim slAsyncFunction2 = Async Function() f = Await t2 Dim mlAsyncSub = Async Sub() Await t1 End Sub Dim mlAsyncFunction1 = Async Function() Await t1 End Function Dim mlAsyncFunction2 = Async Function() Await t1 Return Await t2 End Function End Sub End Module]]>) Dim lambdas = tree.GetRoot().DescendantNodes.OfType(Of LambdaExpressionSyntax)().ToArray() Assert.Equal(7, lambdas.Count) Assert.Equal(4, lambdas.Count(Function(l) SyntaxFacts.IsSingleLineLambdaExpression(l.Kind))) Assert.Equal(SyntaxKind.ExpressionStatement, CType(lambdas(0), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(0), SingleLineLambdaExpressionSyntax).Body, ExpressionStatementSyntax).Expression.Kind) Assert.Equal(SyntaxKind.SimpleAssignmentStatement, CType(lambdas(1), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(1), SingleLineLambdaExpressionSyntax).Body, AssignmentStatementSyntax).Right.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(lambdas(2), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.EqualsExpression, CType(lambdas(3), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(3), SingleLineLambdaExpressionSyntax).Body, BinaryExpressionSyntax).Right.Kind) Assert.Equal(3, lambdas.Count(Function(l) SyntaxFacts.IsMultiLineLambdaExpression(l.Kind))) End Sub <Fact> Public Sub ParseAsyncWithNesting() Dim tree = VisualBasicSyntaxTree.ParseText(<![CDATA[ Imports Async = System.Threading.Tasks.Task Class C Public Const Async As Integer = 0 <Async(Async)> Async Function M() As Async Dim t As Task Await (t) ' Yes Dim lambda1 = Function() Await (t) ' No Dim lambda1a = Sub() Await (t) ' No Dim lambda1b = Async Function() Await t ' Yes Dim lambda1c = Async Function() Await (Sub() Await (Function() Await (Function() (Function() Async Sub() Await t)())()) End Sub) ' Yes, No, No, Yes Return Await t ' Yes End Function [Await] t ' No End Function Sub Await(Optional p = Nothing) Dim t As Task Await (t) ' No Dim lambda1 = Async Function() Await (t) ' Yes Dim lambda1a = Async Sub() Await (t) ' Yes Dim lambda1b = Function() Await (t) ' No Dim lambda1c = Function() Await (Async Sub() Await (Async Function() Await (Async Function() (Function() Sub() Await t)())()) End Sub) ' No, Yes, Yes, No Return Await (t) ' No End Function Await t End Sub Function Await(t) Return Nothing End Function End Class Class AsyncAttribute Inherits Attribute Sub New(p) End Sub End Class]]>.Value) ' Error BC30800: Method arguments must be enclosed in parentheses. Assert.True(Aggregate d In tree.GetDiagnostics() Into All(d.Code = ERRID.ERR_ObsoleteArgumentsNeedParens)) Dim asyncExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax).ToArray() Assert.Equal(9, asyncExpressions.Count) Dim invocationExpression = tree.GetRoot().DescendantNodes.OfType(Of InvocationExpressionSyntax).ToArray() Assert.Equal(9, asyncExpressions.Count) Dim allParsedExpressions = tree.GetRoot().DescendantNodes.OfType(Of ExpressionSyntax)() Dim parsedExpressions = From expression In allParsedExpressions Where expression.Kind = SyntaxKind.AwaitExpression OrElse (expression.Kind = SyntaxKind.IdentifierName AndAlso DirectCast(expression, IdentifierNameSyntax).Identifier.ValueText.Equals("Await")) Order By expression.Position Select expression.Kind Dim expected = {SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName} Assert.Equal(expected, parsedExpressions) End Sub <Fact> Public Sub ParseAwaitInScriptingAndInteractive() Dim source = " Dim i = Await T + Await(T) ' Yes, Yes Dim l = Sub() Await T ' No End Sub Function M() Return Await T ' No End Function Async Sub N() Await T ' Yes Await(T) ' Yes End Sub Async Function F() Return Await(T) ' Yes End Function" Dim tree = VisualBasicSyntaxTree.ParseText(source, options:=TestOptions.Script) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax).ToArray() Assert.Equal(5, awaitExpressions.Count) Dim awaitParsedAsIdentifier = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax).Where(Function(id) id.Identifier.ValueText.Equals("Await")).ToArray() Assert.Equal(2, awaitParsedAsIdentifier.Count) End Sub End Class
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Analyzers/VisualBasic/Analyzers/UseCollectionInitializer/VisualBasicUseCollectionInitializerDiagnosticAnalyzer.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.Diagnostics Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.UseCollectionInitializer Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseCollectionInitializer <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class VisualBasicUseCollectionInitializerDiagnosticAnalyzer Inherits AbstractUseCollectionInitializerDiagnosticAnalyzer(Of SyntaxKind, ExpressionSyntax, StatementSyntax, ObjectCreationExpressionSyntax, MemberAccessExpressionSyntax, InvocationExpressionSyntax, ExpressionStatementSyntax, VariableDeclaratorSyntax) Protected Overrides Function AreCollectionInitializersSupported(compilation As Compilation) As Boolean Return True End Function Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts Return VisualBasicSyntaxFacts.Instance End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.UseCollectionInitializer Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseCollectionInitializer <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class VisualBasicUseCollectionInitializerDiagnosticAnalyzer Inherits AbstractUseCollectionInitializerDiagnosticAnalyzer(Of SyntaxKind, ExpressionSyntax, StatementSyntax, ObjectCreationExpressionSyntax, MemberAccessExpressionSyntax, InvocationExpressionSyntax, ExpressionStatementSyntax, VariableDeclaratorSyntax) Protected Overrides Function AreCollectionInitializersSupported(compilation As Compilation) As Boolean Return True End Function Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts Return VisualBasicSyntaxFacts.Instance End Function End Class End Namespace
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_PropertyAccessors.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 Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Private MustInherit Class AnonymousTypePropertyAccessorSymbol Inherits SynthesizedPropertyAccessorBase(Of PropertySymbol) Private ReadOnly _returnType As TypeSymbol Public Sub New([property] As PropertySymbol, returnType As TypeSymbol) MyBase.New([property].ContainingType, [property]) _returnType = returnType End Sub Friend NotOverridable Overrides ReadOnly Property BackingFieldSymbol As FieldSymbol Get Return DirectCast(Me.m_propertyOrEvent, AnonymousTypePropertySymbol).AssociatedField End Get End Property Protected Overrides Function GenerateMetadataName() As String Return Binder.GetAccessorName(m_propertyOrEvent.MetadataName, Me.MethodKind, Me.IsCompilationOutputWinMdObj()) End Function Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' Dev11 adds DebuggerNonUserCode; there is no reason to do so since: ' - we emit no debug info for the body ' - the code doesn't call any user code that could inspect the stack and find the accessor's frame ' - the code doesn't throw exceptions whose stack frames we would need to hide ' ' C# also doesn't add DebuggerHidden nor DebuggerNonUserCode attributes. End Sub Friend NotOverridable Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend NotOverridable Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class Private NotInheritable Class AnonymousTypePropertyGetAccessorSymbol Inherits AnonymousTypePropertyAccessorSymbol Public Sub New([property] As PropertySymbol) MyBase.New([property], [property].Type) End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertyGet End Get End Property End Class Private NotInheritable Class AnonymousTypePropertySetAccessorSymbol Inherits AnonymousTypePropertyAccessorSymbol Private _parameters As ImmutableArray(Of ParameterSymbol) Public Sub New([property] As PropertySymbol, voidTypeSymbol As TypeSymbol) MyBase.New([property], voidTypeSymbol) _parameters = ImmutableArray.Create(Of ParameterSymbol)( New SynthesizedParameterSymbol(Me, m_propertyOrEvent.Type, 0, False, StringConstants.ValueParameterName)) End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertySet End Get End Property 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 System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Private MustInherit Class AnonymousTypePropertyAccessorSymbol Inherits SynthesizedPropertyAccessorBase(Of PropertySymbol) Private ReadOnly _returnType As TypeSymbol Public Sub New([property] As PropertySymbol, returnType As TypeSymbol) MyBase.New([property].ContainingType, [property]) _returnType = returnType End Sub Friend NotOverridable Overrides ReadOnly Property BackingFieldSymbol As FieldSymbol Get Return DirectCast(Me.m_propertyOrEvent, AnonymousTypePropertySymbol).AssociatedField End Get End Property Protected Overrides Function GenerateMetadataName() As String Return Binder.GetAccessorName(m_propertyOrEvent.MetadataName, Me.MethodKind, Me.IsCompilationOutputWinMdObj()) End Function Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' Dev11 adds DebuggerNonUserCode; there is no reason to do so since: ' - we emit no debug info for the body ' - the code doesn't call any user code that could inspect the stack and find the accessor's frame ' - the code doesn't throw exceptions whose stack frames we would need to hide ' ' C# also doesn't add DebuggerHidden nor DebuggerNonUserCode attributes. End Sub Friend NotOverridable Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend NotOverridable Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class Private NotInheritable Class AnonymousTypePropertyGetAccessorSymbol Inherits AnonymousTypePropertyAccessorSymbol Public Sub New([property] As PropertySymbol) MyBase.New([property], [property].Type) End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertyGet End Get End Property End Class Private NotInheritable Class AnonymousTypePropertySetAccessorSymbol Inherits AnonymousTypePropertyAccessorSymbol Private _parameters As ImmutableArray(Of ParameterSymbol) Public Sub New([property] As PropertySymbol, voidTypeSymbol As TypeSymbol) MyBase.New([property], voidTypeSymbol) _parameters = ImmutableArray.Create(Of ParameterSymbol)( New SynthesizedParameterSymbol(Me, m_propertyOrEvent.Type, 0, False, StringConstants.ValueParameterName)) End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertySet End Get End Property End Class End Class End Namespace
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_DateAndTime.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.Globalization Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpCompletionCommandHandlerTests_DateAndTime <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsShownWithDefaultFormatStringAfterTypingFirstQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString($$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("""") Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString(""G)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsNotShownAfterTypingEndingQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString(" $$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("""") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsShownWithDefaultFormatStringAfterTypingFormattingComponentColon(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(":") Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:G}"";", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsNotShownAfterTypingColonWithinFormattingComponent(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:hh$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(":") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString(""G"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString(":ff$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString("":FF"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("f$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("hh:mm:$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNullableDateTimeCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime? d) { d?.ToString("hh:mm:$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:G}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = @$""Text {d:G}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:ff$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:FF}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:ff$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = @$""Text {d:FF}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $@"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:hh:mm:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:hh:mm:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {date:f$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {date:f$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpCompletionCommandHandlerTests_DateAndTime <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsShownWithDefaultFormatStringAfterTypingFirstQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString($$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("""") Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString(""G)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsNotShownAfterTypingEndingQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString(" $$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("""") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsShownWithDefaultFormatStringAfterTypingFormattingComponentColon(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(":") Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:G}"";", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsNotShownAfterTypingColonWithinFormattingComponent(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:hh$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(":") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString(""G"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString(":ff$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString("":FF"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("f$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("hh:mm:$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNullableDateTimeCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime? d) { d?.ToString("hh:mm:$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:G}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = @$""Text {d:G}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:ff$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:FF}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:ff$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = @$""Text {d:FF}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $@"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:hh:mm:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:hh:mm:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {date:f$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {date:f$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingSymbolExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal static class UnitTestingSymbolExtensions { public static string GetSymbolKeyString(this ISymbol symbol, CancellationToken cancellationToken) => SymbolKey.Create(symbol, cancellationToken).ToString(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal static class UnitTestingSymbolExtensions { public static string GetSymbolKeyString(this ISymbol symbol, CancellationToken cancellationToken) => SymbolKey.Create(symbol, cancellationToken).ToString(); } }
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Workspaces/Core/Portable/Diagnostics/HostDiagnosticAnalyzers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal sealed class HostDiagnosticAnalyzers { /// <summary> /// Key is <see cref="AnalyzerReference.Id"/>. /// /// We use the key to de-duplicate analyzer references if they are referenced from multiple places. /// </summary> private readonly ImmutableDictionary<object, AnalyzerReference> _hostAnalyzerReferencesMap; /// <summary> /// Key is the language the <see cref="DiagnosticAnalyzer"/> supports and key for the second map is analyzer reference identity and /// <see cref="DiagnosticAnalyzer"/> for that assembly reference. /// /// Entry will be lazily filled in. /// </summary> private readonly ConcurrentDictionary<string, ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>>> _hostDiagnosticAnalyzersPerLanguageMap; /// <summary> /// Key is <see cref="AnalyzerReference.Id"/>. /// /// Value is set of <see cref="DiagnosticAnalyzer"/> that belong to the <see cref="AnalyzerReference"/>. /// /// We populate it lazily. otherwise, we will bring in all analyzers preemptively /// </summary> private readonly Lazy<ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>>> _lazyHostDiagnosticAnalyzersPerReferenceMap; /// <summary> /// Maps <see cref="LanguageNames"/> to compiler diagnostic analyzers. /// </summary> private ImmutableDictionary<string, DiagnosticAnalyzer> _compilerDiagnosticAnalyzerMap; /// <summary> /// Maps list of analyzer references and <see cref="LanguageNames"/> to <see cref="SkippedHostAnalyzersInfo"/>. /// </summary> /// <remarks> /// TODO: https://github.com/dotnet/roslyn/issues/42848 /// It is quite common for multiple projects to have the same set of analyzer references, yet we will create /// multiple instances of the analyzer list and thus not share the info. /// </remarks> private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, StrongBox<ImmutableDictionary<string, SkippedHostAnalyzersInfo>>> _skippedHostAnalyzers; internal HostDiagnosticAnalyzers(IEnumerable<AnalyzerReference> hostAnalyzerReferences) { _hostAnalyzerReferencesMap = CreateAnalyzerReferencesMap(hostAnalyzerReferences); _hostDiagnosticAnalyzersPerLanguageMap = new ConcurrentDictionary<string, ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>>>(concurrencyLevel: 2, capacity: 2); _lazyHostDiagnosticAnalyzersPerReferenceMap = new Lazy<ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>>>(() => CreateDiagnosticAnalyzersPerReferenceMap(_hostAnalyzerReferencesMap), isThreadSafe: true); _compilerDiagnosticAnalyzerMap = ImmutableDictionary<string, DiagnosticAnalyzer>.Empty; _skippedHostAnalyzers = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, StrongBox<ImmutableDictionary<string, SkippedHostAnalyzersInfo>>>(); } /// <summary> /// It returns a map with <see cref="AnalyzerReference.Id"/> as key and <see cref="AnalyzerReference"/> as value /// </summary> public ImmutableDictionary<object, AnalyzerReference> GetHostAnalyzerReferencesMap() => _hostAnalyzerReferencesMap; /// <summary> /// Get <see cref="AnalyzerReference"/> identity and <see cref="DiagnosticAnalyzer"/>s map for given <paramref name="language"/> /// </summary> public ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> GetOrCreateHostDiagnosticAnalyzersPerReference(string language) => _hostDiagnosticAnalyzersPerLanguageMap.GetOrAdd(language, CreateHostDiagnosticAnalyzersAndBuildMap); public ImmutableDictionary<string, ImmutableArray<DiagnosticDescriptor>> GetDiagnosticDescriptorsPerReference(DiagnosticAnalyzerInfoCache infoCache) { return ConvertReferenceIdentityToName( CreateDiagnosticDescriptorsPerReference(infoCache, _lazyHostDiagnosticAnalyzersPerReferenceMap.Value), _hostAnalyzerReferencesMap); } public ImmutableDictionary<string, ImmutableArray<DiagnosticDescriptor>> GetDiagnosticDescriptorsPerReference(DiagnosticAnalyzerInfoCache infoCache, Project project) { var descriptorPerReference = CreateDiagnosticDescriptorsPerReference(infoCache, CreateDiagnosticAnalyzersPerReference(project)); var map = _hostAnalyzerReferencesMap.AddRange(CreateProjectAnalyzerReferencesMap(project.AnalyzerReferences)); return ConvertReferenceIdentityToName(descriptorPerReference, map); } private static ImmutableDictionary<string, ImmutableArray<DiagnosticDescriptor>> ConvertReferenceIdentityToName( ImmutableDictionary<object, ImmutableArray<DiagnosticDescriptor>> descriptorsPerReference, ImmutableDictionary<object, AnalyzerReference> map) { var builder = ImmutableDictionary.CreateBuilder<string, ImmutableArray<DiagnosticDescriptor>>(); foreach (var (id, descriptors) in descriptorsPerReference) { if (!map.TryGetValue(id, out var reference) || reference == null) { continue; } var displayName = reference.Display ?? WorkspacesResources.Unknown; // if there are duplicates, merge descriptors if (builder.TryGetValue(displayName, out var existing)) { builder[displayName] = existing.AddRange(descriptors); continue; } builder.Add(displayName, descriptors); } return builder.ToImmutable(); } /// <summary> /// Create <see cref="AnalyzerReference"/> identity and <see cref="DiagnosticAnalyzer"/>s map for given <paramref name="project"/> that /// includes both host and project analyzers /// </summary> public ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> CreateDiagnosticAnalyzersPerReference(Project project) { var hostAnalyzerReferences = GetOrCreateHostDiagnosticAnalyzersPerReference(project.Language); var projectAnalyzerReferences = CreateProjectDiagnosticAnalyzersPerReference(project.AnalyzerReferences, project.Language); return MergeDiagnosticAnalyzerMap(hostAnalyzerReferences, projectAnalyzerReferences); } /// <summary> /// Create <see cref="AnalyzerReference"/> identity and <see cref="DiagnosticAnalyzer"/>s map for given <paramref name="project"/> that /// has only project analyzers /// </summary> public ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> CreateProjectDiagnosticAnalyzersPerReference(Project project) => CreateProjectDiagnosticAnalyzersPerReference(project.AnalyzerReferences, project.Language); public ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> CreateProjectDiagnosticAnalyzersPerReference(IReadOnlyList<AnalyzerReference> projectAnalyzerReferences, string language) => CreateDiagnosticAnalyzersPerReferenceMap(CreateProjectAnalyzerReferencesMap(projectAnalyzerReferences), language); /// <summary> /// Return compiler <see cref="DiagnosticAnalyzer"/> for the given language. /// </summary> public DiagnosticAnalyzer? GetCompilerDiagnosticAnalyzer(string language) { _ = GetOrCreateHostDiagnosticAnalyzersPerReference(language); if (_compilerDiagnosticAnalyzerMap.TryGetValue(language, out var compilerAnalyzer)) { return compilerAnalyzer; } return null; } private ImmutableDictionary<object, AnalyzerReference> CreateProjectAnalyzerReferencesMap(IReadOnlyList<AnalyzerReference> projectAnalyzerReferences) => CreateAnalyzerReferencesMap(projectAnalyzerReferences.Where(reference => !_hostAnalyzerReferencesMap.ContainsKey(reference.Id))); private static ImmutableDictionary<object, ImmutableArray<DiagnosticDescriptor>> CreateDiagnosticDescriptorsPerReference( DiagnosticAnalyzerInfoCache infoCache, ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> analyzersMap) { var builder = ImmutableDictionary.CreateBuilder<object, ImmutableArray<DiagnosticDescriptor>>(); foreach (var (referenceId, analyzers) in analyzersMap) { var descriptors = ImmutableArray.CreateBuilder<DiagnosticDescriptor>(); foreach (var analyzer in analyzers) { // given map should be in good shape. no duplication. no null and etc descriptors.AddRange(infoCache.GetDiagnosticDescriptors(analyzer)); } // there can't be duplication since _hostAnalyzerReferenceMap is already de-duplicated. builder.Add(referenceId, descriptors.ToImmutable()); } return builder.ToImmutable(); } private ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> CreateHostDiagnosticAnalyzersAndBuildMap(string language) { Contract.ThrowIfNull(language); var builder = ImmutableDictionary.CreateBuilder<object, ImmutableArray<DiagnosticAnalyzer>>(); foreach (var (referenceIdentity, reference) in _hostAnalyzerReferencesMap) { var analyzers = reference.GetAnalyzers(language); if (analyzers.Length == 0) { continue; } UpdateCompilerAnalyzerMapIfNeeded(language, analyzers); // there can't be duplication since _hostAnalyzerReferenceMap is already de-duplicated. builder.Add(referenceIdentity, analyzers); } return builder.ToImmutable(); } private void UpdateCompilerAnalyzerMapIfNeeded(string language, ImmutableArray<DiagnosticAnalyzer> analyzers) { if (_compilerDiagnosticAnalyzerMap.ContainsKey(language)) { return; } foreach (var analyzer in analyzers) { if (analyzer.IsCompilerAnalyzer()) { ImmutableInterlocked.GetOrAdd(ref _compilerDiagnosticAnalyzerMap, language, analyzer); return; } } } private static ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> CreateDiagnosticAnalyzersPerReferenceMap( IDictionary<object, AnalyzerReference> analyzerReferencesMap, string? language = null) { var builder = ImmutableDictionary.CreateBuilder<object, ImmutableArray<DiagnosticAnalyzer>>(); foreach (var reference in analyzerReferencesMap) { var analyzers = language == null ? reference.Value.GetAnalyzersForAllLanguages() : reference.Value.GetAnalyzers(language); if (analyzers.Length == 0) { continue; } // input "analyzerReferencesMap" is a dictionary, so there will be no duplication here. builder.Add(reference.Key, analyzers.WhereNotNull().ToImmutableArray()); } return builder.ToImmutable(); } private static ImmutableDictionary<object, AnalyzerReference> CreateAnalyzerReferencesMap(IEnumerable<AnalyzerReference> analyzerReferences) { var builder = ImmutableDictionary.CreateBuilder<object, AnalyzerReference>(); foreach (var reference in analyzerReferences) { var key = reference.Id; // filter out duplicated analyzer reference if (builder.ContainsKey(key)) { continue; } builder.Add(key, reference); } return builder.ToImmutable(); } private static ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> MergeDiagnosticAnalyzerMap( ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> map1, ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> map2) { var current = map1; var seen = new HashSet<DiagnosticAnalyzer>(map1.Values.SelectMany(v => v)); foreach (var (referenceIdentity, analyzers) in map2) { if (map1.ContainsKey(referenceIdentity)) { continue; } current = current.Add(referenceIdentity, analyzers.Where(a => seen.Add(a)).ToImmutableArray()); } return current; } public SkippedHostAnalyzersInfo GetSkippedAnalyzersInfo(Project project, DiagnosticAnalyzerInfoCache infoCache) { var box = _skippedHostAnalyzers.GetOrCreateValue(project.AnalyzerReferences); if (box.Value != null && box.Value.TryGetValue(project.Language, out var info)) { return info; } lock (box) { box.Value ??= ImmutableDictionary<string, SkippedHostAnalyzersInfo>.Empty; if (!box.Value.TryGetValue(project.Language, out info)) { info = SkippedHostAnalyzersInfo.Create(this, project.AnalyzerReferences, project.Language, infoCache); box.Value = box.Value.Add(project.Language, info); } return info; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal sealed class HostDiagnosticAnalyzers { /// <summary> /// Key is <see cref="AnalyzerReference.Id"/>. /// /// We use the key to de-duplicate analyzer references if they are referenced from multiple places. /// </summary> private readonly ImmutableDictionary<object, AnalyzerReference> _hostAnalyzerReferencesMap; /// <summary> /// Key is the language the <see cref="DiagnosticAnalyzer"/> supports and key for the second map is analyzer reference identity and /// <see cref="DiagnosticAnalyzer"/> for that assembly reference. /// /// Entry will be lazily filled in. /// </summary> private readonly ConcurrentDictionary<string, ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>>> _hostDiagnosticAnalyzersPerLanguageMap; /// <summary> /// Key is <see cref="AnalyzerReference.Id"/>. /// /// Value is set of <see cref="DiagnosticAnalyzer"/> that belong to the <see cref="AnalyzerReference"/>. /// /// We populate it lazily. otherwise, we will bring in all analyzers preemptively /// </summary> private readonly Lazy<ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>>> _lazyHostDiagnosticAnalyzersPerReferenceMap; /// <summary> /// Maps <see cref="LanguageNames"/> to compiler diagnostic analyzers. /// </summary> private ImmutableDictionary<string, DiagnosticAnalyzer> _compilerDiagnosticAnalyzerMap; /// <summary> /// Maps list of analyzer references and <see cref="LanguageNames"/> to <see cref="SkippedHostAnalyzersInfo"/>. /// </summary> /// <remarks> /// TODO: https://github.com/dotnet/roslyn/issues/42848 /// It is quite common for multiple projects to have the same set of analyzer references, yet we will create /// multiple instances of the analyzer list and thus not share the info. /// </remarks> private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, StrongBox<ImmutableDictionary<string, SkippedHostAnalyzersInfo>>> _skippedHostAnalyzers; internal HostDiagnosticAnalyzers(IEnumerable<AnalyzerReference> hostAnalyzerReferences) { _hostAnalyzerReferencesMap = CreateAnalyzerReferencesMap(hostAnalyzerReferences); _hostDiagnosticAnalyzersPerLanguageMap = new ConcurrentDictionary<string, ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>>>(concurrencyLevel: 2, capacity: 2); _lazyHostDiagnosticAnalyzersPerReferenceMap = new Lazy<ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>>>(() => CreateDiagnosticAnalyzersPerReferenceMap(_hostAnalyzerReferencesMap), isThreadSafe: true); _compilerDiagnosticAnalyzerMap = ImmutableDictionary<string, DiagnosticAnalyzer>.Empty; _skippedHostAnalyzers = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, StrongBox<ImmutableDictionary<string, SkippedHostAnalyzersInfo>>>(); } /// <summary> /// It returns a map with <see cref="AnalyzerReference.Id"/> as key and <see cref="AnalyzerReference"/> as value /// </summary> public ImmutableDictionary<object, AnalyzerReference> GetHostAnalyzerReferencesMap() => _hostAnalyzerReferencesMap; /// <summary> /// Get <see cref="AnalyzerReference"/> identity and <see cref="DiagnosticAnalyzer"/>s map for given <paramref name="language"/> /// </summary> public ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> GetOrCreateHostDiagnosticAnalyzersPerReference(string language) => _hostDiagnosticAnalyzersPerLanguageMap.GetOrAdd(language, CreateHostDiagnosticAnalyzersAndBuildMap); public ImmutableDictionary<string, ImmutableArray<DiagnosticDescriptor>> GetDiagnosticDescriptorsPerReference(DiagnosticAnalyzerInfoCache infoCache) { return ConvertReferenceIdentityToName( CreateDiagnosticDescriptorsPerReference(infoCache, _lazyHostDiagnosticAnalyzersPerReferenceMap.Value), _hostAnalyzerReferencesMap); } public ImmutableDictionary<string, ImmutableArray<DiagnosticDescriptor>> GetDiagnosticDescriptorsPerReference(DiagnosticAnalyzerInfoCache infoCache, Project project) { var descriptorPerReference = CreateDiagnosticDescriptorsPerReference(infoCache, CreateDiagnosticAnalyzersPerReference(project)); var map = _hostAnalyzerReferencesMap.AddRange(CreateProjectAnalyzerReferencesMap(project.AnalyzerReferences)); return ConvertReferenceIdentityToName(descriptorPerReference, map); } private static ImmutableDictionary<string, ImmutableArray<DiagnosticDescriptor>> ConvertReferenceIdentityToName( ImmutableDictionary<object, ImmutableArray<DiagnosticDescriptor>> descriptorsPerReference, ImmutableDictionary<object, AnalyzerReference> map) { var builder = ImmutableDictionary.CreateBuilder<string, ImmutableArray<DiagnosticDescriptor>>(); foreach (var (id, descriptors) in descriptorsPerReference) { if (!map.TryGetValue(id, out var reference) || reference == null) { continue; } var displayName = reference.Display ?? WorkspacesResources.Unknown; // if there are duplicates, merge descriptors if (builder.TryGetValue(displayName, out var existing)) { builder[displayName] = existing.AddRange(descriptors); continue; } builder.Add(displayName, descriptors); } return builder.ToImmutable(); } /// <summary> /// Create <see cref="AnalyzerReference"/> identity and <see cref="DiagnosticAnalyzer"/>s map for given <paramref name="project"/> that /// includes both host and project analyzers /// </summary> public ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> CreateDiagnosticAnalyzersPerReference(Project project) { var hostAnalyzerReferences = GetOrCreateHostDiagnosticAnalyzersPerReference(project.Language); var projectAnalyzerReferences = CreateProjectDiagnosticAnalyzersPerReference(project.AnalyzerReferences, project.Language); return MergeDiagnosticAnalyzerMap(hostAnalyzerReferences, projectAnalyzerReferences); } /// <summary> /// Create <see cref="AnalyzerReference"/> identity and <see cref="DiagnosticAnalyzer"/>s map for given <paramref name="project"/> that /// has only project analyzers /// </summary> public ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> CreateProjectDiagnosticAnalyzersPerReference(Project project) => CreateProjectDiagnosticAnalyzersPerReference(project.AnalyzerReferences, project.Language); public ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> CreateProjectDiagnosticAnalyzersPerReference(IReadOnlyList<AnalyzerReference> projectAnalyzerReferences, string language) => CreateDiagnosticAnalyzersPerReferenceMap(CreateProjectAnalyzerReferencesMap(projectAnalyzerReferences), language); /// <summary> /// Return compiler <see cref="DiagnosticAnalyzer"/> for the given language. /// </summary> public DiagnosticAnalyzer? GetCompilerDiagnosticAnalyzer(string language) { _ = GetOrCreateHostDiagnosticAnalyzersPerReference(language); if (_compilerDiagnosticAnalyzerMap.TryGetValue(language, out var compilerAnalyzer)) { return compilerAnalyzer; } return null; } private ImmutableDictionary<object, AnalyzerReference> CreateProjectAnalyzerReferencesMap(IReadOnlyList<AnalyzerReference> projectAnalyzerReferences) => CreateAnalyzerReferencesMap(projectAnalyzerReferences.Where(reference => !_hostAnalyzerReferencesMap.ContainsKey(reference.Id))); private static ImmutableDictionary<object, ImmutableArray<DiagnosticDescriptor>> CreateDiagnosticDescriptorsPerReference( DiagnosticAnalyzerInfoCache infoCache, ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> analyzersMap) { var builder = ImmutableDictionary.CreateBuilder<object, ImmutableArray<DiagnosticDescriptor>>(); foreach (var (referenceId, analyzers) in analyzersMap) { var descriptors = ImmutableArray.CreateBuilder<DiagnosticDescriptor>(); foreach (var analyzer in analyzers) { // given map should be in good shape. no duplication. no null and etc descriptors.AddRange(infoCache.GetDiagnosticDescriptors(analyzer)); } // there can't be duplication since _hostAnalyzerReferenceMap is already de-duplicated. builder.Add(referenceId, descriptors.ToImmutable()); } return builder.ToImmutable(); } private ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> CreateHostDiagnosticAnalyzersAndBuildMap(string language) { Contract.ThrowIfNull(language); var builder = ImmutableDictionary.CreateBuilder<object, ImmutableArray<DiagnosticAnalyzer>>(); foreach (var (referenceIdentity, reference) in _hostAnalyzerReferencesMap) { var analyzers = reference.GetAnalyzers(language); if (analyzers.Length == 0) { continue; } UpdateCompilerAnalyzerMapIfNeeded(language, analyzers); // there can't be duplication since _hostAnalyzerReferenceMap is already de-duplicated. builder.Add(referenceIdentity, analyzers); } return builder.ToImmutable(); } private void UpdateCompilerAnalyzerMapIfNeeded(string language, ImmutableArray<DiagnosticAnalyzer> analyzers) { if (_compilerDiagnosticAnalyzerMap.ContainsKey(language)) { return; } foreach (var analyzer in analyzers) { if (analyzer.IsCompilerAnalyzer()) { ImmutableInterlocked.GetOrAdd(ref _compilerDiagnosticAnalyzerMap, language, analyzer); return; } } } private static ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> CreateDiagnosticAnalyzersPerReferenceMap( IDictionary<object, AnalyzerReference> analyzerReferencesMap, string? language = null) { var builder = ImmutableDictionary.CreateBuilder<object, ImmutableArray<DiagnosticAnalyzer>>(); foreach (var reference in analyzerReferencesMap) { var analyzers = language == null ? reference.Value.GetAnalyzersForAllLanguages() : reference.Value.GetAnalyzers(language); if (analyzers.Length == 0) { continue; } // input "analyzerReferencesMap" is a dictionary, so there will be no duplication here. builder.Add(reference.Key, analyzers.WhereNotNull().ToImmutableArray()); } return builder.ToImmutable(); } private static ImmutableDictionary<object, AnalyzerReference> CreateAnalyzerReferencesMap(IEnumerable<AnalyzerReference> analyzerReferences) { var builder = ImmutableDictionary.CreateBuilder<object, AnalyzerReference>(); foreach (var reference in analyzerReferences) { var key = reference.Id; // filter out duplicated analyzer reference if (builder.ContainsKey(key)) { continue; } builder.Add(key, reference); } return builder.ToImmutable(); } private static ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> MergeDiagnosticAnalyzerMap( ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> map1, ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> map2) { var current = map1; var seen = new HashSet<DiagnosticAnalyzer>(map1.Values.SelectMany(v => v)); foreach (var (referenceIdentity, analyzers) in map2) { if (map1.ContainsKey(referenceIdentity)) { continue; } current = current.Add(referenceIdentity, analyzers.Where(a => seen.Add(a)).ToImmutableArray()); } return current; } public SkippedHostAnalyzersInfo GetSkippedAnalyzersInfo(Project project, DiagnosticAnalyzerInfoCache infoCache) { var box = _skippedHostAnalyzers.GetOrCreateValue(project.AnalyzerReferences); if (box.Value != null && box.Value.TryGetValue(project.Language, out var info)) { return info; } lock (box) { box.Value ??= ImmutableDictionary<string, SkippedHostAnalyzersInfo>.Empty; if (!box.Value.TryGetValue(project.Language, out info)) { info = SkippedHostAnalyzersInfo.Create(this, project.AnalyzerReferences, project.Language, infoCache); box.Value = box.Value.Add(project.Language, info); } return info; } } } }
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Compilers/CSharp/Portable/Syntax/BlockSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class BlockSyntax { public BlockSyntax Update(SyntaxToken openBraceToken, SyntaxList<StatementSyntax> statements, SyntaxToken closeBraceToken) => Update(AttributeLists, openBraceToken, statements, closeBraceToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static BlockSyntax Block(SyntaxToken openBraceToken, SyntaxList<StatementSyntax> statements, SyntaxToken closeBraceToken) => Block(attributeLists: default, openBraceToken, statements, closeBraceToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class BlockSyntax { public BlockSyntax Update(SyntaxToken openBraceToken, SyntaxList<StatementSyntax> statements, SyntaxToken closeBraceToken) => Update(AttributeLists, openBraceToken, statements, closeBraceToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static BlockSyntax Block(SyntaxToken openBraceToken, SyntaxList<StatementSyntax> statements, SyntaxToken closeBraceToken) => Block(attributeLists: default, openBraceToken, statements, closeBraceToken); } }
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Tools/ExternalAccess/FSharp/xlf/ExternalAccessFSharpResources.ko.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ko" original="../ExternalAccessFSharpResources.resx"> <body> <trans-unit id="AddAssemblyReference"> <source>Add an assembly reference to '{0}'</source> <target state="translated">'{0}'에 어셈블리 참조 추가</target> <note /> </trans-unit> <trans-unit id="AddNewKeyword"> <source>Add 'new' keyword</source> <target state="translated">'new' 키워드 추가</target> <note /> </trans-unit> <trans-unit id="AddProjectReference"> <source>Add a project reference to '{0}'</source> <target state="translated">'{0}'에 프로젝트 참조 추가</target> <note /> </trans-unit> <trans-unit id="CannotDetermineSymbol"> <source>Cannot determine the symbol under the caret</source> <target state="translated">캐럿에서 기호를 확인할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="CannotNavigateUnknown"> <source>Cannot navigate to the requested location</source> <target state="translated">요청한 위치로 이동할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="ExceptionsHeader"> <source>Exceptions:</source> <target state="translated">예외:</target> <note /> </trans-unit> <trans-unit id="FSharpDisposablesClassificationType"> <source>F# Disposable Types</source> <target state="translated">F# 삭제 가능한 형식</target> <note /> </trans-unit> <trans-unit id="FSharpFunctionsOrMethodsClassificationType"> <source>F# Functions / Methods</source> <target state="translated">F# 함수/메서드</target> <note /> </trans-unit> <trans-unit id="FSharpMutableVarsClassificationType"> <source>F# Mutable Variables / Reference Cells</source> <target state="translated">F# 변경 가능한 변수/참조 셀</target> <note /> </trans-unit> <trans-unit id="FSharpPrintfFormatClassificationType"> <source>F# Printf Format</source> <target state="translated">F# Printf 형식</target> <note /> </trans-unit> <trans-unit id="FSharpPropertiesClassificationType"> <source>F# Properties</source> <target state="translated">F# 속성</target> <note /> </trans-unit> <trans-unit id="GenericParametersHeader"> <source>Generic parameters:</source> <target state="translated">제네릭 매개 변수:</target> <note /> </trans-unit> <trans-unit id="ImplementInterface"> <source>Implement interface</source> <target state="translated">인터페이스 구현</target> <note /> </trans-unit> <trans-unit id="ImplementInterfaceWithoutTypeAnnotation"> <source>Implement interface without type annotation</source> <target state="translated">형식 주석 없이 인터페이스 구현</target> <note /> </trans-unit> <trans-unit id="LocatingSymbol"> <source>Locating the symbol under the caret...</source> <target state="translated">캐럿에서 기호를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="NameCanBeSimplified"> <source>Name can be simplified.</source> <target state="translated">이름을 간단하게 줄일 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="NavigateToFailed"> <source>Navigate to symbol failed: {0}</source> <target state="translated">기호로 이동하지 못함: {0}</target> <note /> </trans-unit> <trans-unit id="NavigatingTo"> <source>Navigating to symbol...</source> <target state="translated">기호로 이동하는 중...</target> <note /> </trans-unit> <trans-unit id="PrefixValueNameWithUnderscore"> <source>Prefix '{0}' with underscore</source> <target state="translated">'{0}' 앞에 밑줄 붙이기</target> <note /> </trans-unit> <trans-unit id="RemoveUnusedOpens"> <source>Remove unused open declarations</source> <target state="translated">사용되지 않는 열려 있는 선언 제거</target> <note /> </trans-unit> <trans-unit id="RenameValueToDoubleUnderscore"> <source>Rename '{0}' to '__'</source> <target state="translated">'{0}'에서 '__'로 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="RenameValueToUnderscore"> <source>Rename '{0}' to '_'</source> <target state="translated">'{0}'에서 '_'로 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="SimplifyName"> <source>Simplify name</source> <target state="translated">이름 단순화</target> <note /> </trans-unit> <trans-unit id="TheValueIsUnused"> <source>The value is unused</source> <target state="translated">값이 사용되지 않음</target> <note /> </trans-unit> <trans-unit id="UnusedOpens"> <source>Open declaration can be removed.</source> <target state="translated">열려 있는 선언은 제거할 수 있습니다.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ko" original="../ExternalAccessFSharpResources.resx"> <body> <trans-unit id="AddAssemblyReference"> <source>Add an assembly reference to '{0}'</source> <target state="translated">'{0}'에 어셈블리 참조 추가</target> <note /> </trans-unit> <trans-unit id="AddNewKeyword"> <source>Add 'new' keyword</source> <target state="translated">'new' 키워드 추가</target> <note /> </trans-unit> <trans-unit id="AddProjectReference"> <source>Add a project reference to '{0}'</source> <target state="translated">'{0}'에 프로젝트 참조 추가</target> <note /> </trans-unit> <trans-unit id="CannotDetermineSymbol"> <source>Cannot determine the symbol under the caret</source> <target state="translated">캐럿에서 기호를 확인할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="CannotNavigateUnknown"> <source>Cannot navigate to the requested location</source> <target state="translated">요청한 위치로 이동할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="ExceptionsHeader"> <source>Exceptions:</source> <target state="translated">예외:</target> <note /> </trans-unit> <trans-unit id="FSharpDisposablesClassificationType"> <source>F# Disposable Types</source> <target state="translated">F# 삭제 가능한 형식</target> <note /> </trans-unit> <trans-unit id="FSharpFunctionsOrMethodsClassificationType"> <source>F# Functions / Methods</source> <target state="translated">F# 함수/메서드</target> <note /> </trans-unit> <trans-unit id="FSharpMutableVarsClassificationType"> <source>F# Mutable Variables / Reference Cells</source> <target state="translated">F# 변경 가능한 변수/참조 셀</target> <note /> </trans-unit> <trans-unit id="FSharpPrintfFormatClassificationType"> <source>F# Printf Format</source> <target state="translated">F# Printf 형식</target> <note /> </trans-unit> <trans-unit id="FSharpPropertiesClassificationType"> <source>F# Properties</source> <target state="translated">F# 속성</target> <note /> </trans-unit> <trans-unit id="GenericParametersHeader"> <source>Generic parameters:</source> <target state="translated">제네릭 매개 변수:</target> <note /> </trans-unit> <trans-unit id="ImplementInterface"> <source>Implement interface</source> <target state="translated">인터페이스 구현</target> <note /> </trans-unit> <trans-unit id="ImplementInterfaceWithoutTypeAnnotation"> <source>Implement interface without type annotation</source> <target state="translated">형식 주석 없이 인터페이스 구현</target> <note /> </trans-unit> <trans-unit id="LocatingSymbol"> <source>Locating the symbol under the caret...</source> <target state="translated">캐럿에서 기호를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="NameCanBeSimplified"> <source>Name can be simplified.</source> <target state="translated">이름을 간단하게 줄일 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="NavigateToFailed"> <source>Navigate to symbol failed: {0}</source> <target state="translated">기호로 이동하지 못함: {0}</target> <note /> </trans-unit> <trans-unit id="NavigatingTo"> <source>Navigating to symbol...</source> <target state="translated">기호로 이동하는 중...</target> <note /> </trans-unit> <trans-unit id="PrefixValueNameWithUnderscore"> <source>Prefix '{0}' with underscore</source> <target state="translated">'{0}' 앞에 밑줄 붙이기</target> <note /> </trans-unit> <trans-unit id="RemoveUnusedOpens"> <source>Remove unused open declarations</source> <target state="translated">사용되지 않는 열려 있는 선언 제거</target> <note /> </trans-unit> <trans-unit id="RenameValueToDoubleUnderscore"> <source>Rename '{0}' to '__'</source> <target state="translated">'{0}'에서 '__'로 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="RenameValueToUnderscore"> <source>Rename '{0}' to '_'</source> <target state="translated">'{0}'에서 '_'로 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="SimplifyName"> <source>Simplify name</source> <target state="translated">이름 단순화</target> <note /> </trans-unit> <trans-unit id="TheValueIsUnused"> <source>The value is unused</source> <target state="translated">값이 사용되지 않음</target> <note /> </trans-unit> <trans-unit id="UnusedOpens"> <source>Open declaration can be removed.</source> <target state="translated">열려 있는 선언은 제거할 수 있습니다.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ja" original="../CSharpFeaturesResources.resx"> <body> <trans-unit id="Add_await"> <source>Add 'await'</source> <target state="translated">'await' の追加</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_await_and_ConfigureAwaitFalse"> <source>Add 'await' and 'ConfigureAwait(false)'</source> <target state="translated">'await' と 'ConfigureAwait(false)' の追加</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_missing_usings"> <source>Add missing usings</source> <target state="translated">不足している using を追加する</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_remove_braces_for_single_line_control_statements"> <source>Add/remove braces for single-line control statements</source> <target state="translated">単一行のコントロール ステートメントに対する波かっこの追加/削除を行います</target> <note /> </trans-unit> <trans-unit id="Allow_unsafe_code_in_this_project"> <source>Allow unsafe code in this project</source> <target state="translated">このプロジェクトでアンセーフ コードを許可する</target> <note /> </trans-unit> <trans-unit id="Apply_expression_block_body_preferences"> <source>Apply expression/block body preferences</source> <target state="translated">式/ブロック本体の基本設定を適用します</target> <note /> </trans-unit> <trans-unit id="Apply_implicit_explicit_type_preferences"> <source>Apply implicit/explicit type preferences</source> <target state="translated">暗黙的/明示的な型の基本設定を適用します</target> <note /> </trans-unit> <trans-unit id="Apply_inline_out_variable_preferences"> <source>Apply inline 'out' variables preferences</source> <target state="translated">インラインの 'out' 変数の基本設定を適用します</target> <note /> </trans-unit> <trans-unit id="Apply_language_framework_type_preferences"> <source>Apply language/framework type preferences</source> <target state="translated">言語/フレームワークの型の基本設定を適用します</target> <note /> </trans-unit> <trans-unit id="Apply_this_qualification_preferences"> <source>Apply 'this.' qualification preferences</source> <target state="translated">'this.' 修飾の基本設定を適用します</target> <note /> </trans-unit> <trans-unit id="Apply_using_directive_placement_preferences"> <source>Apply preferred 'using' placement preferences</source> <target state="translated">優先する 'using' 配置設定を適用する</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Assign_out_parameters"> <source>Assign 'out' parameters</source> <target state="translated">'out' パラメーターの割り当て</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_out_parameters_at_start"> <source>Assign 'out' parameters (at start)</source> <target state="translated">'out' パラメーターの割り当て (開始時)</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_to_0"> <source>Assign to '{0}'</source> <target state="translated">"{0}" に割り当て</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration"> <source>Autoselect disabled due to potential pattern variable declaration.</source> <target state="translated">パターン変数宣言の可能性があるため、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="Change_to_as_expression"> <source>Change to 'as' expression</source> <target state="translated">'as' 式に変更</target> <note /> </trans-unit> <trans-unit id="Change_to_cast"> <source>Change to cast</source> <target state="translated">キャストに変更</target> <note /> </trans-unit> <trans-unit id="Compare_to_0"> <source>Compare to '{0}'</source> <target state="translated">"{0}" と比較</target> <note /> </trans-unit> <trans-unit id="Convert_to_method"> <source>Convert to method</source> <target state="translated">メソッドに変換</target> <note /> </trans-unit> <trans-unit id="Convert_to_regular_string"> <source>Convert to regular string</source> <target state="translated">正規文字列に変換する</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_expression"> <source>Convert to 'switch' expression</source> <target state="translated">'switch' 式に変換する</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_statement"> <source>Convert to 'switch' statement</source> <target state="translated">'switch' ステートメントに変換</target> <note /> </trans-unit> <trans-unit id="Convert_to_verbatim_string"> <source>Convert to verbatim string</source> <target state="translated">逐語的文字列に変換する</target> <note /> </trans-unit> <trans-unit id="Declare_as_nullable"> <source>Declare as nullable</source> <target state="translated">Null 許容型として宣言する</target> <note /> </trans-unit> <trans-unit id="Fix_return_type"> <source>Fix return type</source> <target state="translated">戻り値の型の修正</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">インラインの一時変数</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">競合が検出されました。</target> <note /> </trans-unit> <trans-unit id="Make_container_async"> <source>Make container 'async'</source> <target state="new">Make container 'async'</target> <note>{Locked="async"} "async" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_private_field_readonly_when_possible"> <source>Make private fields readonly when possible</source> <target state="translated">可能な場合、private フィールドを読み取り専用にする</target> <note /> </trans-unit> <trans-unit id="Make_ref_struct"> <source>Make 'ref struct'</source> <target state="translated">'ref struct' を作成します</target> <note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Remove_in_keyword"> <source>Remove 'in' keyword</source> <target state="translated">'in' キーワードを削除します</target> <note>{Locked="in"} "in" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Remove_new_modifier"> <source>Remove 'new' modifier</source> <target state="translated">'new' 修飾子の削除</target> <note /> </trans-unit> <trans-unit id="Reverse_for_statement"> <source>Reverse 'for' statement</source> <target state="translated">'for' ステートメントの反転</target> <note>{Locked="for"} "for" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Simplify_lambda_expression"> <source>Simplify lambda expression</source> <target state="translated">ラムダ式の簡略化</target> <note /> </trans-unit> <trans-unit id="Simplify_all_occurrences"> <source>Simplify all occurrences</source> <target state="translated">すべての出現箇所を簡素化します</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">アクセシビリティ修飾子を並べ替える</target> <note /> </trans-unit> <trans-unit id="Unseal_class_0"> <source>Unseal class '{0}'</source> <target state="translated">クラス '{0}' のシールを解除</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_into_conditional_method_call"> <source>Warning: Inlining temporary into conditional method call.</source> <target state="translated">警告: 一時メソッド呼び出しを条件付きメソッド呼び出しにインライン展開しています。</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning"> <source>Warning: Inlining temporary variable may change code meaning.</source> <target state="translated">警告: 一時変数をインライン化すると、コードの意味が変わる可能性があります。</target> <note /> </trans-unit> <trans-unit id="asynchronous_foreach_statement"> <source>asynchronous foreach statement</source> <target state="translated">非同期の foreach ステートメント</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="asynchronous_using_declaration"> <source>asynchronous using declaration</source> <target state="translated">非同期の using 宣言</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="extern_alias"> <source>extern alias</source> <target state="translated">extern エイリアス</target> <note /> </trans-unit> <trans-unit id="lambda_expression"> <source>&lt;lambda expression&gt;</source> <target state="translated">&lt;ラムダ式&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration"> <source>Autoselect disabled due to potential lambda declaration.</source> <target state="translated">ラムダが宣言された可能性があるため、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="local_variable_declaration"> <source>local variable declaration</source> <target state="translated">ローカル変数宣言</target> <note /> </trans-unit> <trans-unit id="member_name"> <source>&lt;member name&gt; = </source> <target state="translated">&lt;メンバー名&gt; =</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation"> <source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source> <target state="translated">明示的に指定された匿名型メンバーの作成である可能性があるため、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="element_name"> <source>&lt;element name&gt; : </source> <target state="translated">&lt;要素名&gt;:</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation"> <source>Autoselect disabled due to possible tuple type element creation.</source> <target state="translated">タプル型の要素が作成された可能性があるため、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="pattern_variable"> <source>&lt;pattern variable&gt;</source> <target state="translated">&lt;pattern variable&gt;</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>&lt;range variable&gt;</source> <target state="translated">&lt;範囲変数&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration"> <source>Autoselect disabled due to potential range variable declaration.</source> <target state="translated">範囲変数宣言の可能性があるため、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">名前 '{0}' の単純化</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">メンバーのアクセス '{0}' を単純化します</target> <note /> </trans-unit> <trans-unit id="Remove_this_qualification"> <source>Remove 'this' qualification</source> <target state="translated">this' 修飾子を削除します</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">名前を簡略化できます</target> <note /> </trans-unit> <trans-unit id="Can_t_determine_valid_range_of_statements_to_extract"> <source>Can't determine valid range of statements to extract</source> <target state="translated">抽出するステートメントの有効な範囲を決定できません</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">返されないコード パスがあります</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_node"> <source>Selection does not contain a valid node</source> <target state="translated">選択には有効なノードは含まれません</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="translated">選択が無効です。</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_token"> <source>Selection does not contain a valid token.</source> <target state="translated">選択には有効なトークンは含まれません。</target> <note /> </trans-unit> <trans-unit id="No_valid_selection_to_perform_extraction"> <source>No valid selection to perform extraction.</source> <target state="translated">抽出を行うための有効な選択がありません。</target> <note /> </trans-unit> <trans-unit id="No_common_root_node_for_extraction"> <source>No common root node for extraction.</source> <target state="translated">抽出するための一般的なルート ノードがありません。</target> <note /> </trans-unit> <trans-unit id="Contains_invalid_selection"> <source>Contains invalid selection.</source> <target state="translated">無効な選択が含まれています。</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_syntactic_errors"> <source>The selection contains syntactic errors</source> <target state="translated">選択に構文エラーが含まれています</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_cross_over_preprocessor_directives"> <source>Selection can not cross over preprocessor directives.</source> <target state="translated">選択範囲はプリプロセッサ ディレクティブ上を通過できません。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_yield_statement"> <source>Selection can not contain a yield statement.</source> <target state="translated">選択範囲に yield ステートメントを含めることはできません。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_throw_statement"> <source>Selection can not contain throw statement.</source> <target state="translated">選択範囲に throw ステートメントを含めることはできません。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression"> <source>Selection can not be part of constant initializer expression.</source> <target state="translated">選択範囲を定数の初期化子式の一部にすることはできません。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_pattern_expression"> <source>Selection can not contain a pattern expression.</source> <target state="translated">選択に、パターン式を含めることはできません。</target> <note /> </trans-unit> <trans-unit id="The_selected_code_is_inside_an_unsafe_context"> <source>The selected code is inside an unsafe context.</source> <target state="translated">選択されたコードは unsafe コンテキストの内側にあります。</target> <note /> </trans-unit> <trans-unit id="No_valid_statement_range_to_extract"> <source>No valid statement range to extract</source> <target state="translated">抽出する有効なステートメントの範囲がありません</target> <note /> </trans-unit> <trans-unit id="deprecated"> <source>deprecated</source> <target state="translated">非推奨</target> <note /> </trans-unit> <trans-unit id="extension"> <source>extension</source> <target state="translated">拡張子</target> <note /> </trans-unit> <trans-unit id="awaitable"> <source>awaitable</source> <target state="translated">待機可能</target> <note /> </trans-unit> <trans-unit id="awaitable_extension"> <source>awaitable, extension</source> <target state="translated">待機可能、拡張子</target> <note /> </trans-unit> <trans-unit id="Organize_Usings"> <source>Organize Usings</source> <target state="translated">using の整理</target> <note /> </trans-unit> <trans-unit id="Insert_await"> <source>Insert 'await'.</source> <target state="translated">await' を挿入します。</target> <note /> </trans-unit> <trans-unit id="Make_0_return_Task_instead_of_void"> <source>Make {0} return Task instead of void.</source> <target state="translated">{0} が void ではなくタスクを返すようにします。</target> <note /> </trans-unit> <trans-unit id="Change_return_type_from_0_to_1"> <source>Change return type from {0} to {1}</source> <target state="translated">戻り値の型を {0} から {1} に変更する</target> <note /> </trans-unit> <trans-unit id="Replace_return_with_yield_return"> <source>Replace return with yield return</source> <target state="translated">戻り値を 'yield' の戻り値に置き換える</target> <note /> </trans-unit> <trans-unit id="Generate_explicit_conversion_operator_in_0"> <source>Generate explicit conversion operator in '{0}'</source> <target state="translated">明示的な変換演算子を '{0}' に生成します</target> <note /> </trans-unit> <trans-unit id="Generate_implicit_conversion_operator_in_0"> <source>Generate implicit conversion operator in '{0}'</source> <target state="translated">暗黙的な変換演算子を '{0}' に生成します</target> <note /> </trans-unit> <trans-unit id="record_"> <source>record</source> <target state="translated">レコード</target> <note /> </trans-unit> <trans-unit id="record_struct"> <source>record struct</source> <target state="new">record struct</target> <note /> </trans-unit> <trans-unit id="switch_statement"> <source>switch statement</source> <target state="translated">switch ステートメント</target> <note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="switch_statement_case_clause"> <source>switch statement case clause</source> <target state="translated">switch ステートメントの case 句</target> <note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="try_block"> <source>try block</source> <target state="translated">try ブロック</target> <note>{Locked="try"} "try" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="catch_clause"> <source>catch clause</source> <target state="translated">catch 句</target> <note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="filter_clause"> <source>filter clause</source> <target state="translated">フィルター句</target> <note /> </trans-unit> <trans-unit id="finally_clause"> <source>finally clause</source> <target state="translated">finally 句</target> <note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="fixed_statement"> <source>fixed statement</source> <target state="translated">fixed ステートメント</target> <note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_declaration"> <source>using declaration</source> <target state="translated">using 宣言</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_statement"> <source>using statement</source> <target state="translated">using ステートメント</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lock_statement"> <source>lock statement</source> <target state="translated">lock ステートメント</target> <note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="foreach_statement"> <source>foreach statement</source> <target state="translated">foreach ステートメント</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="checked_statement"> <source>checked statement</source> <target state="translated">checked ステートメント</target> <note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="unchecked_statement"> <source>unchecked statement</source> <target state="translated">unchecked ステートメント</target> <note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="await_expression"> <source>await expression</source> <target state="translated">await 式</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lambda"> <source>lambda</source> <target state="translated">ラムダ</target> <note /> </trans-unit> <trans-unit id="anonymous_method"> <source>anonymous method</source> <target state="translated">匿名メソッド</target> <note /> </trans-unit> <trans-unit id="from_clause"> <source>from clause</source> <target state="translated">from 句</target> <note /> </trans-unit> <trans-unit id="join_clause"> <source>join clause</source> <target state="translated">join 句</target> <note>{Locked="join"} "join" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="let_clause"> <source>let clause</source> <target state="translated">let 句</target> <note>{Locked="let"} "let" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="where_clause"> <source>where clause</source> <target state="translated">where 句</target> <note>{Locked="where"} "where" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="orderby_clause"> <source>orderby clause</source> <target state="translated">orderby 句</target> <note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="select_clause"> <source>select clause</source> <target state="translated">select 句</target> <note>{Locked="select"} "select" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="groupby_clause"> <source>groupby clause</source> <target state="translated">groupby 句</target> <note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="query_body"> <source>query body</source> <target state="translated">クエリ本体</target> <note /> </trans-unit> <trans-unit id="into_clause"> <source>into clause</source> <target state="translated">into 句</target> <note>{Locked="into"} "into" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="is_pattern"> <source>is pattern</source> <target state="translated">is パターン</target> <note>{Locked="is"} "is" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="deconstruction"> <source>deconstruction</source> <target state="translated">分解</target> <note /> </trans-unit> <trans-unit id="tuple"> <source>tuple</source> <target state="translated">タプル</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">ローカル関数</target> <note /> </trans-unit> <trans-unit id="out_var"> <source>out variable</source> <target state="translated">out 変数</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="ref_local_or_expression"> <source>ref local or expression</source> <target state="translated">ref ローカルまたは式</target> <note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="global_statement"> <source>global statement</source> <target state="translated">global ステートメント</target> <note>{Locked="global"} "global" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_directive"> <source>using directive</source> <target state="translated">using ディレクティブ</target> <note /> </trans-unit> <trans-unit id="event_field"> <source>event field</source> <target state="translated">イベント フィールド</target> <note /> </trans-unit> <trans-unit id="conversion_operator"> <source>conversion operator</source> <target state="translated">変換演算子</target> <note /> </trans-unit> <trans-unit id="destructor"> <source>destructor</source> <target state="translated">デストラクター</target> <note /> </trans-unit> <trans-unit id="indexer"> <source>indexer</source> <target state="translated">インデクサー</target> <note /> </trans-unit> <trans-unit id="property_getter"> <source>property getter</source> <target state="translated">プロパティ ゲッター</target> <note /> </trans-unit> <trans-unit id="indexer_getter"> <source>indexer getter</source> <target state="translated">インデクサー ゲッター</target> <note /> </trans-unit> <trans-unit id="property_setter"> <source>property setter</source> <target state="translated">プロパティ set アクセス操作子</target> <note /> </trans-unit> <trans-unit id="indexer_setter"> <source>indexer setter</source> <target state="translated">インデクサー set アクセス操作子</target> <note /> </trans-unit> <trans-unit id="attribute_target"> <source>attribute target</source> <target state="translated">属性ターゲット</target> <note /> </trans-unit> <trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments"> <source>'{0}' does not contain a constructor that takes that many arguments.</source> <target state="translated">'{0}' には、多数の引数を指定できるコンストラクターがありません。</target> <note /> </trans-unit> <trans-unit id="The_name_0_does_not_exist_in_the_current_context"> <source>The name '{0}' does not exist in the current context.</source> <target state="translated">名前 '{0}' は、現在のコンテキストに存在しません。</target> <note /> </trans-unit> <trans-unit id="Hide_base_member"> <source>Hide base member</source> <target state="translated">基本メンバーを非表示にします</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">プロパティ</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_namespace_declaration"> <source>Autoselect disabled due to namespace declaration.</source> <target state="translated">名前空間宣言により、Autoselect は無効です。</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;名前空間名&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_type_declaration"> <source>Autoselect disabled due to type declaration.</source> <target state="translated">型宣言が原因で、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration"> <source>Autoselect disabled due to possible deconstruction declaration.</source> <target state="translated">分解宣言の可能性により、自動選択が無効になりました。</target> <note /> </trans-unit> <trans-unit id="Upgrade_this_project_to_csharp_language_version_0"> <source>Upgrade this project to C# language version '{0}'</source> <target state="translated">このプロジェクトを C# 言語バージョン '{0}' にアップグレードする</target> <note /> </trans-unit> <trans-unit id="Upgrade_all_csharp_projects_to_language_version_0"> <source>Upgrade all C# projects to language version '{0}'</source> <target state="translated">すべての C# プロジェクトを言語バージョン '{0}' にアップグレードする</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;クラス名&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;インターフェイス名&gt;</target> <note /> </trans-unit> <trans-unit id="designation_name"> <source>&lt;designation name&gt;</source> <target state="translated">&lt;指定名&gt;</target> <note /> </trans-unit> <trans-unit id="struct_name"> <source>&lt;struct name&gt;</source> <target state="translated">&lt;構造体名&gt;</target> <note /> </trans-unit> <trans-unit id="Make_method_async"> <source>Make method async</source> <target state="translated">メソッドを非同期にします</target> <note /> </trans-unit> <trans-unit id="Make_method_async_remain_void"> <source>Make method async (stay void)</source> <target state="translated">メソッドを非同期にする (void を維持)</target> <note /> </trans-unit> <trans-unit id="Name"> <source>&lt;Name&gt;</source> <target state="translated">&lt;名前&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_member_declaration"> <source>Autoselect disabled due to member declaration</source> <target state="translated">メンバー宣言が原因で自動選択が無効になりました</target> <note /> </trans-unit> <trans-unit id="Suggested_name"> <source>(Suggested name)</source> <target state="translated">(推奨される名前)</target> <note /> </trans-unit> <trans-unit id="Remove_unused_function"> <source>Remove unused function</source> <target state="translated">使用されていない関数を削除します</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string"> <source>Add parentheses</source> <target state="translated">括弧を追加します</target> <note /> </trans-unit> <trans-unit id="Convert_to_foreach"> <source>Convert to 'foreach'</source> <target state="translated">'foreach' に変換する</target> <note /> </trans-unit> <trans-unit id="Convert_to_for"> <source>Convert to 'for'</source> <target state="translated">'for' に変換する</target> <note /> </trans-unit> <trans-unit id="Invert_if"> <source>Invert if</source> <target state="translated">if を反転する</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add [Obsolete]</source> <target state="translated">追加 [廃止]</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use '{0}'</source> <target state="translated">'{0}' を使用します</target> <note /> </trans-unit> <trans-unit id="Introduce_using_statement"> <source>Introduce 'using' statement</source> <target state="translated">'using' ステートメントを導入します</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_break_statement"> <source>yield break statement</source> <target state="translated">yield break ステートメント</target> <note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_return_statement"> <source>yield return statement</source> <target state="translated">yield return ステートメント</target> <note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ja" original="../CSharpFeaturesResources.resx"> <body> <trans-unit id="Add_await"> <source>Add 'await'</source> <target state="translated">'await' の追加</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_await_and_ConfigureAwaitFalse"> <source>Add 'await' and 'ConfigureAwait(false)'</source> <target state="translated">'await' と 'ConfigureAwait(false)' の追加</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_missing_usings"> <source>Add missing usings</source> <target state="translated">不足している using を追加する</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_remove_braces_for_single_line_control_statements"> <source>Add/remove braces for single-line control statements</source> <target state="translated">単一行のコントロール ステートメントに対する波かっこの追加/削除を行います</target> <note /> </trans-unit> <trans-unit id="Allow_unsafe_code_in_this_project"> <source>Allow unsafe code in this project</source> <target state="translated">このプロジェクトでアンセーフ コードを許可する</target> <note /> </trans-unit> <trans-unit id="Apply_expression_block_body_preferences"> <source>Apply expression/block body preferences</source> <target state="translated">式/ブロック本体の基本設定を適用します</target> <note /> </trans-unit> <trans-unit id="Apply_implicit_explicit_type_preferences"> <source>Apply implicit/explicit type preferences</source> <target state="translated">暗黙的/明示的な型の基本設定を適用します</target> <note /> </trans-unit> <trans-unit id="Apply_inline_out_variable_preferences"> <source>Apply inline 'out' variables preferences</source> <target state="translated">インラインの 'out' 変数の基本設定を適用します</target> <note /> </trans-unit> <trans-unit id="Apply_language_framework_type_preferences"> <source>Apply language/framework type preferences</source> <target state="translated">言語/フレームワークの型の基本設定を適用します</target> <note /> </trans-unit> <trans-unit id="Apply_this_qualification_preferences"> <source>Apply 'this.' qualification preferences</source> <target state="translated">'this.' 修飾の基本設定を適用します</target> <note /> </trans-unit> <trans-unit id="Apply_using_directive_placement_preferences"> <source>Apply preferred 'using' placement preferences</source> <target state="translated">優先する 'using' 配置設定を適用する</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Assign_out_parameters"> <source>Assign 'out' parameters</source> <target state="translated">'out' パラメーターの割り当て</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_out_parameters_at_start"> <source>Assign 'out' parameters (at start)</source> <target state="translated">'out' パラメーターの割り当て (開始時)</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_to_0"> <source>Assign to '{0}'</source> <target state="translated">"{0}" に割り当て</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration"> <source>Autoselect disabled due to potential pattern variable declaration.</source> <target state="translated">パターン変数宣言の可能性があるため、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="Change_to_as_expression"> <source>Change to 'as' expression</source> <target state="translated">'as' 式に変更</target> <note /> </trans-unit> <trans-unit id="Change_to_cast"> <source>Change to cast</source> <target state="translated">キャストに変更</target> <note /> </trans-unit> <trans-unit id="Compare_to_0"> <source>Compare to '{0}'</source> <target state="translated">"{0}" と比較</target> <note /> </trans-unit> <trans-unit id="Convert_to_method"> <source>Convert to method</source> <target state="translated">メソッドに変換</target> <note /> </trans-unit> <trans-unit id="Convert_to_regular_string"> <source>Convert to regular string</source> <target state="translated">正規文字列に変換する</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_expression"> <source>Convert to 'switch' expression</source> <target state="translated">'switch' 式に変換する</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_statement"> <source>Convert to 'switch' statement</source> <target state="translated">'switch' ステートメントに変換</target> <note /> </trans-unit> <trans-unit id="Convert_to_verbatim_string"> <source>Convert to verbatim string</source> <target state="translated">逐語的文字列に変換する</target> <note /> </trans-unit> <trans-unit id="Declare_as_nullable"> <source>Declare as nullable</source> <target state="translated">Null 許容型として宣言する</target> <note /> </trans-unit> <trans-unit id="Fix_return_type"> <source>Fix return type</source> <target state="translated">戻り値の型の修正</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">インラインの一時変数</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">競合が検出されました。</target> <note /> </trans-unit> <trans-unit id="Make_container_async"> <source>Make container 'async'</source> <target state="new">Make container 'async'</target> <note>{Locked="async"} "async" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_private_field_readonly_when_possible"> <source>Make private fields readonly when possible</source> <target state="translated">可能な場合、private フィールドを読み取り専用にする</target> <note /> </trans-unit> <trans-unit id="Make_ref_struct"> <source>Make 'ref struct'</source> <target state="translated">'ref struct' を作成します</target> <note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Remove_in_keyword"> <source>Remove 'in' keyword</source> <target state="translated">'in' キーワードを削除します</target> <note>{Locked="in"} "in" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Remove_new_modifier"> <source>Remove 'new' modifier</source> <target state="translated">'new' 修飾子の削除</target> <note /> </trans-unit> <trans-unit id="Reverse_for_statement"> <source>Reverse 'for' statement</source> <target state="translated">'for' ステートメントの反転</target> <note>{Locked="for"} "for" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Simplify_lambda_expression"> <source>Simplify lambda expression</source> <target state="translated">ラムダ式の簡略化</target> <note /> </trans-unit> <trans-unit id="Simplify_all_occurrences"> <source>Simplify all occurrences</source> <target state="translated">すべての出現箇所を簡素化します</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">アクセシビリティ修飾子を並べ替える</target> <note /> </trans-unit> <trans-unit id="Unseal_class_0"> <source>Unseal class '{0}'</source> <target state="translated">クラス '{0}' のシールを解除</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_into_conditional_method_call"> <source>Warning: Inlining temporary into conditional method call.</source> <target state="translated">警告: 一時メソッド呼び出しを条件付きメソッド呼び出しにインライン展開しています。</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning"> <source>Warning: Inlining temporary variable may change code meaning.</source> <target state="translated">警告: 一時変数をインライン化すると、コードの意味が変わる可能性があります。</target> <note /> </trans-unit> <trans-unit id="asynchronous_foreach_statement"> <source>asynchronous foreach statement</source> <target state="translated">非同期の foreach ステートメント</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="asynchronous_using_declaration"> <source>asynchronous using declaration</source> <target state="translated">非同期の using 宣言</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="extern_alias"> <source>extern alias</source> <target state="translated">extern エイリアス</target> <note /> </trans-unit> <trans-unit id="lambda_expression"> <source>&lt;lambda expression&gt;</source> <target state="translated">&lt;ラムダ式&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration"> <source>Autoselect disabled due to potential lambda declaration.</source> <target state="translated">ラムダが宣言された可能性があるため、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="local_variable_declaration"> <source>local variable declaration</source> <target state="translated">ローカル変数宣言</target> <note /> </trans-unit> <trans-unit id="member_name"> <source>&lt;member name&gt; = </source> <target state="translated">&lt;メンバー名&gt; =</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation"> <source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source> <target state="translated">明示的に指定された匿名型メンバーの作成である可能性があるため、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="element_name"> <source>&lt;element name&gt; : </source> <target state="translated">&lt;要素名&gt;:</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation"> <source>Autoselect disabled due to possible tuple type element creation.</source> <target state="translated">タプル型の要素が作成された可能性があるため、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="pattern_variable"> <source>&lt;pattern variable&gt;</source> <target state="translated">&lt;pattern variable&gt;</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>&lt;range variable&gt;</source> <target state="translated">&lt;範囲変数&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration"> <source>Autoselect disabled due to potential range variable declaration.</source> <target state="translated">範囲変数宣言の可能性があるため、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">名前 '{0}' の単純化</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">メンバーのアクセス '{0}' を単純化します</target> <note /> </trans-unit> <trans-unit id="Remove_this_qualification"> <source>Remove 'this' qualification</source> <target state="translated">this' 修飾子を削除します</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">名前を簡略化できます</target> <note /> </trans-unit> <trans-unit id="Can_t_determine_valid_range_of_statements_to_extract"> <source>Can't determine valid range of statements to extract</source> <target state="translated">抽出するステートメントの有効な範囲を決定できません</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">返されないコード パスがあります</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_node"> <source>Selection does not contain a valid node</source> <target state="translated">選択には有効なノードは含まれません</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="translated">選択が無効です。</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_token"> <source>Selection does not contain a valid token.</source> <target state="translated">選択には有効なトークンは含まれません。</target> <note /> </trans-unit> <trans-unit id="No_valid_selection_to_perform_extraction"> <source>No valid selection to perform extraction.</source> <target state="translated">抽出を行うための有効な選択がありません。</target> <note /> </trans-unit> <trans-unit id="No_common_root_node_for_extraction"> <source>No common root node for extraction.</source> <target state="translated">抽出するための一般的なルート ノードがありません。</target> <note /> </trans-unit> <trans-unit id="Contains_invalid_selection"> <source>Contains invalid selection.</source> <target state="translated">無効な選択が含まれています。</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_syntactic_errors"> <source>The selection contains syntactic errors</source> <target state="translated">選択に構文エラーが含まれています</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_cross_over_preprocessor_directives"> <source>Selection can not cross over preprocessor directives.</source> <target state="translated">選択範囲はプリプロセッサ ディレクティブ上を通過できません。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_yield_statement"> <source>Selection can not contain a yield statement.</source> <target state="translated">選択範囲に yield ステートメントを含めることはできません。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_throw_statement"> <source>Selection can not contain throw statement.</source> <target state="translated">選択範囲に throw ステートメントを含めることはできません。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression"> <source>Selection can not be part of constant initializer expression.</source> <target state="translated">選択範囲を定数の初期化子式の一部にすることはできません。</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_pattern_expression"> <source>Selection can not contain a pattern expression.</source> <target state="translated">選択に、パターン式を含めることはできません。</target> <note /> </trans-unit> <trans-unit id="The_selected_code_is_inside_an_unsafe_context"> <source>The selected code is inside an unsafe context.</source> <target state="translated">選択されたコードは unsafe コンテキストの内側にあります。</target> <note /> </trans-unit> <trans-unit id="No_valid_statement_range_to_extract"> <source>No valid statement range to extract</source> <target state="translated">抽出する有効なステートメントの範囲がありません</target> <note /> </trans-unit> <trans-unit id="deprecated"> <source>deprecated</source> <target state="translated">非推奨</target> <note /> </trans-unit> <trans-unit id="extension"> <source>extension</source> <target state="translated">拡張子</target> <note /> </trans-unit> <trans-unit id="awaitable"> <source>awaitable</source> <target state="translated">待機可能</target> <note /> </trans-unit> <trans-unit id="awaitable_extension"> <source>awaitable, extension</source> <target state="translated">待機可能、拡張子</target> <note /> </trans-unit> <trans-unit id="Organize_Usings"> <source>Organize Usings</source> <target state="translated">using の整理</target> <note /> </trans-unit> <trans-unit id="Insert_await"> <source>Insert 'await'.</source> <target state="translated">await' を挿入します。</target> <note /> </trans-unit> <trans-unit id="Make_0_return_Task_instead_of_void"> <source>Make {0} return Task instead of void.</source> <target state="translated">{0} が void ではなくタスクを返すようにします。</target> <note /> </trans-unit> <trans-unit id="Change_return_type_from_0_to_1"> <source>Change return type from {0} to {1}</source> <target state="translated">戻り値の型を {0} から {1} に変更する</target> <note /> </trans-unit> <trans-unit id="Replace_return_with_yield_return"> <source>Replace return with yield return</source> <target state="translated">戻り値を 'yield' の戻り値に置き換える</target> <note /> </trans-unit> <trans-unit id="Generate_explicit_conversion_operator_in_0"> <source>Generate explicit conversion operator in '{0}'</source> <target state="translated">明示的な変換演算子を '{0}' に生成します</target> <note /> </trans-unit> <trans-unit id="Generate_implicit_conversion_operator_in_0"> <source>Generate implicit conversion operator in '{0}'</source> <target state="translated">暗黙的な変換演算子を '{0}' に生成します</target> <note /> </trans-unit> <trans-unit id="record_"> <source>record</source> <target state="translated">レコード</target> <note /> </trans-unit> <trans-unit id="record_struct"> <source>record struct</source> <target state="new">record struct</target> <note /> </trans-unit> <trans-unit id="switch_statement"> <source>switch statement</source> <target state="translated">switch ステートメント</target> <note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="switch_statement_case_clause"> <source>switch statement case clause</source> <target state="translated">switch ステートメントの case 句</target> <note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="try_block"> <source>try block</source> <target state="translated">try ブロック</target> <note>{Locked="try"} "try" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="catch_clause"> <source>catch clause</source> <target state="translated">catch 句</target> <note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="filter_clause"> <source>filter clause</source> <target state="translated">フィルター句</target> <note /> </trans-unit> <trans-unit id="finally_clause"> <source>finally clause</source> <target state="translated">finally 句</target> <note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="fixed_statement"> <source>fixed statement</source> <target state="translated">fixed ステートメント</target> <note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_declaration"> <source>using declaration</source> <target state="translated">using 宣言</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_statement"> <source>using statement</source> <target state="translated">using ステートメント</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lock_statement"> <source>lock statement</source> <target state="translated">lock ステートメント</target> <note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="foreach_statement"> <source>foreach statement</source> <target state="translated">foreach ステートメント</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="checked_statement"> <source>checked statement</source> <target state="translated">checked ステートメント</target> <note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="unchecked_statement"> <source>unchecked statement</source> <target state="translated">unchecked ステートメント</target> <note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="await_expression"> <source>await expression</source> <target state="translated">await 式</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lambda"> <source>lambda</source> <target state="translated">ラムダ</target> <note /> </trans-unit> <trans-unit id="anonymous_method"> <source>anonymous method</source> <target state="translated">匿名メソッド</target> <note /> </trans-unit> <trans-unit id="from_clause"> <source>from clause</source> <target state="translated">from 句</target> <note /> </trans-unit> <trans-unit id="join_clause"> <source>join clause</source> <target state="translated">join 句</target> <note>{Locked="join"} "join" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="let_clause"> <source>let clause</source> <target state="translated">let 句</target> <note>{Locked="let"} "let" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="where_clause"> <source>where clause</source> <target state="translated">where 句</target> <note>{Locked="where"} "where" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="orderby_clause"> <source>orderby clause</source> <target state="translated">orderby 句</target> <note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="select_clause"> <source>select clause</source> <target state="translated">select 句</target> <note>{Locked="select"} "select" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="groupby_clause"> <source>groupby clause</source> <target state="translated">groupby 句</target> <note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="query_body"> <source>query body</source> <target state="translated">クエリ本体</target> <note /> </trans-unit> <trans-unit id="into_clause"> <source>into clause</source> <target state="translated">into 句</target> <note>{Locked="into"} "into" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="is_pattern"> <source>is pattern</source> <target state="translated">is パターン</target> <note>{Locked="is"} "is" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="deconstruction"> <source>deconstruction</source> <target state="translated">分解</target> <note /> </trans-unit> <trans-unit id="tuple"> <source>tuple</source> <target state="translated">タプル</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">ローカル関数</target> <note /> </trans-unit> <trans-unit id="out_var"> <source>out variable</source> <target state="translated">out 変数</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="ref_local_or_expression"> <source>ref local or expression</source> <target state="translated">ref ローカルまたは式</target> <note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="global_statement"> <source>global statement</source> <target state="translated">global ステートメント</target> <note>{Locked="global"} "global" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_directive"> <source>using directive</source> <target state="translated">using ディレクティブ</target> <note /> </trans-unit> <trans-unit id="event_field"> <source>event field</source> <target state="translated">イベント フィールド</target> <note /> </trans-unit> <trans-unit id="conversion_operator"> <source>conversion operator</source> <target state="translated">変換演算子</target> <note /> </trans-unit> <trans-unit id="destructor"> <source>destructor</source> <target state="translated">デストラクター</target> <note /> </trans-unit> <trans-unit id="indexer"> <source>indexer</source> <target state="translated">インデクサー</target> <note /> </trans-unit> <trans-unit id="property_getter"> <source>property getter</source> <target state="translated">プロパティ ゲッター</target> <note /> </trans-unit> <trans-unit id="indexer_getter"> <source>indexer getter</source> <target state="translated">インデクサー ゲッター</target> <note /> </trans-unit> <trans-unit id="property_setter"> <source>property setter</source> <target state="translated">プロパティ set アクセス操作子</target> <note /> </trans-unit> <trans-unit id="indexer_setter"> <source>indexer setter</source> <target state="translated">インデクサー set アクセス操作子</target> <note /> </trans-unit> <trans-unit id="attribute_target"> <source>attribute target</source> <target state="translated">属性ターゲット</target> <note /> </trans-unit> <trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments"> <source>'{0}' does not contain a constructor that takes that many arguments.</source> <target state="translated">'{0}' には、多数の引数を指定できるコンストラクターがありません。</target> <note /> </trans-unit> <trans-unit id="The_name_0_does_not_exist_in_the_current_context"> <source>The name '{0}' does not exist in the current context.</source> <target state="translated">名前 '{0}' は、現在のコンテキストに存在しません。</target> <note /> </trans-unit> <trans-unit id="Hide_base_member"> <source>Hide base member</source> <target state="translated">基本メンバーを非表示にします</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">プロパティ</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_namespace_declaration"> <source>Autoselect disabled due to namespace declaration.</source> <target state="translated">名前空間宣言により、Autoselect は無効です。</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;名前空間名&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_type_declaration"> <source>Autoselect disabled due to type declaration.</source> <target state="translated">型宣言が原因で、自動選択は無効になっています。</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration"> <source>Autoselect disabled due to possible deconstruction declaration.</source> <target state="translated">分解宣言の可能性により、自動選択が無効になりました。</target> <note /> </trans-unit> <trans-unit id="Upgrade_this_project_to_csharp_language_version_0"> <source>Upgrade this project to C# language version '{0}'</source> <target state="translated">このプロジェクトを C# 言語バージョン '{0}' にアップグレードする</target> <note /> </trans-unit> <trans-unit id="Upgrade_all_csharp_projects_to_language_version_0"> <source>Upgrade all C# projects to language version '{0}'</source> <target state="translated">すべての C# プロジェクトを言語バージョン '{0}' にアップグレードする</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;クラス名&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;インターフェイス名&gt;</target> <note /> </trans-unit> <trans-unit id="designation_name"> <source>&lt;designation name&gt;</source> <target state="translated">&lt;指定名&gt;</target> <note /> </trans-unit> <trans-unit id="struct_name"> <source>&lt;struct name&gt;</source> <target state="translated">&lt;構造体名&gt;</target> <note /> </trans-unit> <trans-unit id="Make_method_async"> <source>Make method async</source> <target state="translated">メソッドを非同期にします</target> <note /> </trans-unit> <trans-unit id="Make_method_async_remain_void"> <source>Make method async (stay void)</source> <target state="translated">メソッドを非同期にする (void を維持)</target> <note /> </trans-unit> <trans-unit id="Name"> <source>&lt;Name&gt;</source> <target state="translated">&lt;名前&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_member_declaration"> <source>Autoselect disabled due to member declaration</source> <target state="translated">メンバー宣言が原因で自動選択が無効になりました</target> <note /> </trans-unit> <trans-unit id="Suggested_name"> <source>(Suggested name)</source> <target state="translated">(推奨される名前)</target> <note /> </trans-unit> <trans-unit id="Remove_unused_function"> <source>Remove unused function</source> <target state="translated">使用されていない関数を削除します</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string"> <source>Add parentheses</source> <target state="translated">括弧を追加します</target> <note /> </trans-unit> <trans-unit id="Convert_to_foreach"> <source>Convert to 'foreach'</source> <target state="translated">'foreach' に変換する</target> <note /> </trans-unit> <trans-unit id="Convert_to_for"> <source>Convert to 'for'</source> <target state="translated">'for' に変換する</target> <note /> </trans-unit> <trans-unit id="Invert_if"> <source>Invert if</source> <target state="translated">if を反転する</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add [Obsolete]</source> <target state="translated">追加 [廃止]</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use '{0}'</source> <target state="translated">'{0}' を使用します</target> <note /> </trans-unit> <trans-unit id="Introduce_using_statement"> <source>Introduce 'using' statement</source> <target state="translated">'using' ステートメントを導入します</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_break_statement"> <source>yield break statement</source> <target state="translated">yield break ステートメント</target> <note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_return_statement"> <source>yield return statement</source> <target state="translated">yield return ステートメント</target> <note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/Compilers/Test/Resources/Core/ExpressionCompiler/Windows.Storage.winmd
MZ@ !L!This program cannot be run in DOS mode. $PELT" 0& @ @X&O@`  H.text  `.rsrc@ @@.reloc `@B&H\ "( *BSJB$WindowsRuntime 1.3;CLR v4.0.30319<#~L#Strings #US#GUID$#BlobG 3 /C U&W  p  F  zEAE@'EP {u  !)9IY a iqy%4%S.L.#U.+tC3}C;CCCKESc3}c;cCc[cK[cCkE:&;Ca<Module>Windows.Foundation.MetadatamscorlibWindows.Storage.winmdWindows.StorageIStringableSystem.RuntimeMarshalingTypeCompilerGeneratedAttributeGuidAttributeDebuggableAttributeActivatableAttributeThreadingAttributeVersionAttributeExclusiveToAttributeMarshalingBehaviorAttributeCompilationRelaxationsAttributeDefaultAttributeRuntimeCompatibilityAttributevalueWindows.Foundation.IStringable.ToStringThreadingModelSystemWindows.Foundation<CLR>StorageFolder.ctorSystem.DiagnosticsSystem.Runtime.CompilerServicesDebuggingModesIStorageFolderClassWindowsObject 5:\hKk     ! )     Ez\V4?_ :TWrapNonExceptionThrows<3W~! hüq"Windows.Storage.StorageFolder&& &_CorDllMainmscoree.dll% 0HX@||4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0RInternalNameWindows.Storage.winmdobj(LegalCopyright ZOriginalFilenameWindows.Storage.winmdobj4ProductVersion0.0.0.08Assembly Version0.0.0.0 6
MZ@ !L!This program cannot be run in DOS mode. $PELT" 0& @ @X&O@`  H.text  `.rsrc@ @@.reloc `@B&H\ "( *BSJB$WindowsRuntime 1.3;CLR v4.0.30319<#~L#Strings #US#GUID$#BlobG 3 /C U&W  p  F  zEAE@'EP {u  !)9IY a iqy%4%S.L.#U.+tC3}C;CCCKESc3}c;cCc[cK[cCkE:&;Ca<Module>Windows.Foundation.MetadatamscorlibWindows.Storage.winmdWindows.StorageIStringableSystem.RuntimeMarshalingTypeCompilerGeneratedAttributeGuidAttributeDebuggableAttributeActivatableAttributeThreadingAttributeVersionAttributeExclusiveToAttributeMarshalingBehaviorAttributeCompilationRelaxationsAttributeDefaultAttributeRuntimeCompatibilityAttributevalueWindows.Foundation.IStringable.ToStringThreadingModelSystemWindows.Foundation<CLR>StorageFolder.ctorSystem.DiagnosticsSystem.Runtime.CompilerServicesDebuggingModesIStorageFolderClassWindowsObject 5:\hKk     ! )     Ez\V4?_ :TWrapNonExceptionThrows<3W~! hüq"Windows.Storage.StorageFolder&& &_CorDllMainmscoree.dll% 0HX@||4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0RInternalNameWindows.Storage.winmdobj(LegalCopyright ZOriginalFilenameWindows.Storage.winmdobj4ProductVersion0.0.0.08Assembly Version0.0.0.0 6
-1
dotnet/roslyn
55,074
Move EnC language service implementation down to EditorFeatures
Also removes old interfaces.
tmat
2021-07-23T17:08:06Z
2021-07-27T16:06:51Z
4d107c3266686a06960046eadd299d3ac9b25d81
77e20f412539203837231ef2e31d7699b6cdffdc
Move EnC language service implementation down to EditorFeatures. Also removes old interfaces.
./src/EditorFeatures/CSharpTest/Wrapping/ParameterWrappingTests.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.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.Wrapping; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping { public class ParameterWrappingTests : AbstractWrappingTests { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpWrappingCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSyntaxError() { await TestMissingAsync( @"class C { void Goo([||]int i, int j { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSelection() { await TestMissingAsync( @"class C { void Goo([|int|] i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingInBody() { await TestMissingAsync( @"class C { void Goo(int i, int j) {[||] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingInAttributes() { await TestMissingAsync( @"class C { [||][Attr] void Goo(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithOpenTokenTrailingComment() { await TestMissingAsync( @"class C { void Goo([||]/**/int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithItemLeadingComment() { await TestMissingAsync( @"class C { void Goo([||] /**/int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithItemTrailingComment() { await TestMissingAsync( @"class C { void Goo([||] int i/**/, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithCommaTrailingComment() { await TestMissingAsync( @"class C { void Goo([||] int i,/**/int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithLastItemTrailingComment() { await TestMissingAsync( @"class C { void Goo([||] int i, int j/**/ ) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithCloseTokenLeadingComment() { await TestMissingAsync( @"class C { void Goo([||] int i, int j /**/) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestWithOpenTokenLeadingComment() { await TestInRegularAndScript1Async( @"class C { void Goo/**/([||]int i, int j) { } }", @"class C { void Goo/**/(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestWithCloseTokenTrailingComment() { await TestInRegularAndScript1Async( @"class C { void Goo([||]int i, int j)/**/ { } }", @"class C { void Goo(int i, int j)/**/ { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSingleParameter() { await TestMissingAsync( @"class C { void Goo([||]int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithMultiLineParameter() { await TestMissingAsync( @"class C { void Goo([||]int i, int j = initializer) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader1() { await TestInRegularAndScript1Async( @"class C { [||]void Goo(int i, int j) { } }", @"class C { void Goo(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader2() { await TestInRegularAndScript1Async( @"class C { void [||]Goo(int i, int j) { } }", @"class C { void Goo(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader3() { await TestInRegularAndScript1Async( @"class C { [||]public void Goo(int i, int j) { } }", @"class C { public void Goo(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader4() { await TestInRegularAndScript1Async( @"class C { public void Goo(int i, int j)[||] { } }", @"class C { public void Goo(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestTwoParamWrappingCases() { await TestAllWrappingCasesAsync( @"class C { void Goo([||]int i, int j) { } }", @"class C { void Goo(int i, int j) { } }", @"class C { void Goo( int i, int j) { } }", @"class C { void Goo(int i, int j) { } }", @"class C { void Goo( int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestThreeParamWrappingCases() { await TestAllWrappingCasesAsync( @"class C { void Goo([||]int i, int j, int k) { } }", @"class C { void Goo(int i, int j, int k) { } }", @"class C { void Goo( int i, int j, int k) { } }", @"class C { void Goo(int i, int j, int k) { } }", @"class C { void Goo( int i, int j, int k) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_AllOptions_NoInitialMatches() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int i, int j, int k) { } }", @"class C { void Goo(int i, int j, int k) { } }", @"class C { void Goo( int i, int j, int k) { } }", @"class C { void Goo(int i, int j, int k) { } }", @"class C { void Goo(int i, int j, int k) { } }", @"class C { void Goo( int i, int j, int k) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_ShortIds() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int i, int j, int k, int l, int m, int n) { } }", GetIndentionColumn(30), @"class C { void Goo(int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo( int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo(int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo(int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo( int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo(int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo( int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo(int i, int j, int k, int l, int m, int n) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_VariadicLengthIds() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", GetIndentionColumn(30), @"class C { void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo( int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo( int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo( int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", GetIndentionColumn(30), @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo( int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo( int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo( int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", GetIndentionColumn(20), @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo( int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo( int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_VariadicLengthIds2() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int i, int jj, int kkkk, int lll, int mm, int n) { } }", GetIndentionColumn(30), @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption1() { await TestAllWrappingCasesAsync( @"class C { void Goo([||]int i, int jj, int kkkk, int lll, int mm, int n) { } }", GetIndentionColumn(30), @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption2() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int i, int jj, int kkkk, int lll, int mm, int n) { } }", GetIndentionColumn(30), @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInConstructor() { await TestInRegularAndScript1Async( @"class C { public [||]C(int i, int j) { } }", @"class C { public C(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIndexer() { await TestInRegularAndScript1Async( @"class C { public int [||]this[int i, int j] => 0; }", @"class C { public int this[int i, int j] => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInOperator() { await TestInRegularAndScript1Async( @"class C { public shared int operator [||]+(C c1, C c2) => 0; }", @"class C { public shared int operator +(C c1, C c2) => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInDelegate() { await TestInRegularAndScript1Async( @"class C { public delegate int [||]D(C c1, C c2); }", @"class C { public delegate int D(C c1, C c2); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInParenthesizedLambda() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = ([||]C c, C d) => { }; } }", @"class C { void Goo() { var v = (C c, C d) => { }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInParenthesizedLambda2() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = ([||]c, d) => { }; } }", @"class C { void Goo() { var v = (c, d) => { }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestNotOnSimpleLambda() { await TestMissingAsync( @"class C { void Goo() { var v = [||]c => { }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestLocalFunction() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Local([||]C c, C d) { } } }", @"class C { void Goo() { void Local(C c, C d) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestRecord_Semicolon() { await TestInRegularAndScript1Async( "record R([||]int I, string S);", @"record R(int I, string S);"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestRecord_Braces() { await TestInRegularAndScript1Async( "record R([||]int I, string S) { }", @"record R(int I, string S) { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestRecordStruct_Semicolon() { await TestInRegularAndScript1Async( "record struct R([||]int I, string S);", @"record struct R(int I, string S);", new TestParameters(TestOptions.RegularPreview)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestRecordStruct_Braces() { await TestInRegularAndScript1Async( "record struct R([||]int I, string S) { }", @"record struct R(int I, string S) { }", new TestParameters(TestOptions.RegularPreview)); } } }
// Licensed to the .NET Foundation under one or more 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.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.Wrapping; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping { public class ParameterWrappingTests : AbstractWrappingTests { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpWrappingCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSyntaxError() { await TestMissingAsync( @"class C { void Goo([||]int i, int j { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSelection() { await TestMissingAsync( @"class C { void Goo([|int|] i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingInBody() { await TestMissingAsync( @"class C { void Goo(int i, int j) {[||] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingInAttributes() { await TestMissingAsync( @"class C { [||][Attr] void Goo(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithOpenTokenTrailingComment() { await TestMissingAsync( @"class C { void Goo([||]/**/int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithItemLeadingComment() { await TestMissingAsync( @"class C { void Goo([||] /**/int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithItemTrailingComment() { await TestMissingAsync( @"class C { void Goo([||] int i/**/, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithCommaTrailingComment() { await TestMissingAsync( @"class C { void Goo([||] int i,/**/int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithLastItemTrailingComment() { await TestMissingAsync( @"class C { void Goo([||] int i, int j/**/ ) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithCloseTokenLeadingComment() { await TestMissingAsync( @"class C { void Goo([||] int i, int j /**/) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestWithOpenTokenLeadingComment() { await TestInRegularAndScript1Async( @"class C { void Goo/**/([||]int i, int j) { } }", @"class C { void Goo/**/(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestWithCloseTokenTrailingComment() { await TestInRegularAndScript1Async( @"class C { void Goo([||]int i, int j)/**/ { } }", @"class C { void Goo(int i, int j)/**/ { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSingleParameter() { await TestMissingAsync( @"class C { void Goo([||]int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithMultiLineParameter() { await TestMissingAsync( @"class C { void Goo([||]int i, int j = initializer) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader1() { await TestInRegularAndScript1Async( @"class C { [||]void Goo(int i, int j) { } }", @"class C { void Goo(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader2() { await TestInRegularAndScript1Async( @"class C { void [||]Goo(int i, int j) { } }", @"class C { void Goo(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader3() { await TestInRegularAndScript1Async( @"class C { [||]public void Goo(int i, int j) { } }", @"class C { public void Goo(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInHeader4() { await TestInRegularAndScript1Async( @"class C { public void Goo(int i, int j)[||] { } }", @"class C { public void Goo(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestTwoParamWrappingCases() { await TestAllWrappingCasesAsync( @"class C { void Goo([||]int i, int j) { } }", @"class C { void Goo(int i, int j) { } }", @"class C { void Goo( int i, int j) { } }", @"class C { void Goo(int i, int j) { } }", @"class C { void Goo( int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestThreeParamWrappingCases() { await TestAllWrappingCasesAsync( @"class C { void Goo([||]int i, int j, int k) { } }", @"class C { void Goo(int i, int j, int k) { } }", @"class C { void Goo( int i, int j, int k) { } }", @"class C { void Goo(int i, int j, int k) { } }", @"class C { void Goo( int i, int j, int k) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_AllOptions_NoInitialMatches() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int i, int j, int k) { } }", @"class C { void Goo(int i, int j, int k) { } }", @"class C { void Goo( int i, int j, int k) { } }", @"class C { void Goo(int i, int j, int k) { } }", @"class C { void Goo(int i, int j, int k) { } }", @"class C { void Goo( int i, int j, int k) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_ShortIds() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int i, int j, int k, int l, int m, int n) { } }", GetIndentionColumn(30), @"class C { void Goo(int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo( int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo(int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo(int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo( int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo(int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo( int i, int j, int k, int l, int m, int n) { } }", @"class C { void Goo(int i, int j, int k, int l, int m, int n) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_VariadicLengthIds() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", GetIndentionColumn(30), @"class C { void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo( int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo( int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo( int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }", @"class C { void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", GetIndentionColumn(30), @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo( int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo( int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo( int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", GetIndentionColumn(20), @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo( int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }", @"class C { void Goo( int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_LongWrapping_VariadicLengthIds2() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int i, int jj, int kkkk, int lll, int mm, int n) { } }", GetIndentionColumn(30), @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption1() { await TestAllWrappingCasesAsync( @"class C { void Goo([||]int i, int jj, int kkkk, int lll, int mm, int n) { } }", GetIndentionColumn(30), @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption2() { await TestAllWrappingCasesAsync( @"class C { void Goo([||] int i, int jj, int kkkk, int lll, int mm, int n) { } }", GetIndentionColumn(30), @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo( int i, int jj, int kkkk, int lll, int mm, int n) { } }", @"class C { void Goo(int i, int jj, int kkkk, int lll, int mm, int n) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInConstructor() { await TestInRegularAndScript1Async( @"class C { public [||]C(int i, int j) { } }", @"class C { public C(int i, int j) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIndexer() { await TestInRegularAndScript1Async( @"class C { public int [||]this[int i, int j] => 0; }", @"class C { public int this[int i, int j] => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInOperator() { await TestInRegularAndScript1Async( @"class C { public shared int operator [||]+(C c1, C c2) => 0; }", @"class C { public shared int operator +(C c1, C c2) => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInDelegate() { await TestInRegularAndScript1Async( @"class C { public delegate int [||]D(C c1, C c2); }", @"class C { public delegate int D(C c1, C c2); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInParenthesizedLambda() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = ([||]C c, C d) => { }; } }", @"class C { void Goo() { var v = (C c, C d) => { }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInParenthesizedLambda2() { await TestInRegularAndScript1Async( @"class C { void Goo() { var v = ([||]c, d) => { }; } }", @"class C { void Goo() { var v = (c, d) => { }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestNotOnSimpleLambda() { await TestMissingAsync( @"class C { void Goo() { var v = [||]c => { }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestLocalFunction() { await TestInRegularAndScript1Async( @"class C { void Goo() { void Local([||]C c, C d) { } } }", @"class C { void Goo() { void Local(C c, C d) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestRecord_Semicolon() { await TestInRegularAndScript1Async( "record R([||]int I, string S);", @"record R(int I, string S);"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestRecord_Braces() { await TestInRegularAndScript1Async( "record R([||]int I, string S) { }", @"record R(int I, string S) { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestRecordStruct_Semicolon() { await TestInRegularAndScript1Async( "record struct R([||]int I, string S);", @"record struct R(int I, string S);", new TestParameters(TestOptions.RegularPreview)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestRecordStruct_Braces() { await TestInRegularAndScript1Async( "record struct R([||]int I, string S) { }", @"record struct R(int I, string S) { }", new TestParameters(TestOptions.RegularPreview)); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Def/Implementation/LanguageClient/AbstractInProcLanguageClient.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.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LogHub; using Microsoft.VisualStudio.RpcContracts.Logging; using Microsoft.VisualStudio.Shell.ServiceBroker; using Microsoft.VisualStudio.Threading; using Nerdbank.Streams; using Roslyn.Utilities; using StreamJsonRpc; using VSShell = Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { internal abstract partial class AbstractInProcLanguageClient : ILanguageClient, ILanguageServerFactory, ICapabilitiesProvider { /// <summary> /// A unique, always increasing, ID we use to identify this server in our loghub logs. Needed so that if our /// server is restarted that we can have a new logstream for the new server. /// </summary> private static int s_logHubSessionId; private readonly string? _diagnosticsClientName; private readonly VSShell.IAsyncServiceProvider _asyncServiceProvider; private readonly IThreadingContext _threadingContext; /// <summary> /// Legacy support for LSP push diagnostics. /// </summary> private readonly IDiagnosticService? _diagnosticService; private readonly IAsynchronousOperationListenerProvider _listenerProvider; private readonly AbstractRequestDispatcherFactory _requestDispatcherFactory; private readonly ILspWorkspaceRegistrationService _lspWorkspaceRegistrationService; protected readonly Workspace Workspace; /// <summary> /// Created when <see cref="ActivateAsync"/> is called. /// </summary> private LanguageServerTarget? _languageServer; /// <summary> /// Gets the name of the language client (displayed to the user). /// </summary> public abstract string Name { get; } /// <summary> /// Unused, implementing <see cref="ILanguageClient"/> /// No additional settings are provided for this server, so we do not need any configuration section names. /// </summary> public IEnumerable<string>? ConfigurationSections { get; } /// <summary> /// Gets the initialization options object the client wants to send when 'initialize' message is sent. /// See https://microsoft.github.io/language-server-protocol/specifications/specification-3-14/#initialize /// We do not provide any additional initialization options. /// </summary> public object? InitializationOptions { get; } /// <summary> /// Unused, implementing <see cref="ILanguageClient"/> /// Files that we care about are already provided and watched by the workspace. /// </summary> public IEnumerable<string>? FilesToWatch { get; } public event AsyncEventHandler<EventArgs>? StartAsync; /// <summary> /// Unused, implementing <see cref="ILanguageClient"/> /// </summary> public event AsyncEventHandler<EventArgs>? StopAsync { add { } remove { } } public AbstractInProcLanguageClient( AbstractRequestDispatcherFactory requestDispatcherFactory, VisualStudioWorkspace workspace, IDiagnosticService? diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, VSShell.IAsyncServiceProvider asyncServiceProvider, IThreadingContext threadingContext, string? diagnosticsClientName) { _requestDispatcherFactory = requestDispatcherFactory; Workspace = workspace; _diagnosticService = diagnosticService; _listenerProvider = listenerProvider; _lspWorkspaceRegistrationService = lspWorkspaceRegistrationService; _diagnosticsClientName = diagnosticsClientName; _asyncServiceProvider = asyncServiceProvider; _threadingContext = threadingContext; } public async Task<Connection?> ActivateAsync(CancellationToken cancellationToken) { // HACK HACK HACK: prevent potential crashes/state corruption during load. Fixes // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1261421 // // When we create an LSP server, we compute our server capabilities; this may depend on // reading things like workspace options which will force us to initialize our option persisters. // Unfortunately some of our option persisters currently assert they are first created on the UI // thread. If the first time they're created is because of LSP initialization, we might end up loading // them on a background thread which will throw exceptions and then prevent them from being created // again later. // // The correct fix for this is to fix the threading violations in the option persister code; // asserting a MEF component is constructed on the foreground thread is never allowed, but alas it's // done there. Fixing that isn't difficult but comes with some risk I don't want to take for 16.9; // instead we'll just compute our capabilities here on the UI thread to ensure everything is loaded. // We _could_ consider doing a SwitchToMainThreadAsync in InProcLanguageServer.InitializeAsync // (where the problematic call to GetCapabilites is), but that call is invoked across the StreamJsonRpc // link where it's unclear if VS Threading rules apply. By doing this here, we are dong it in a // VS API that is following VS Threading rules, and it also ensures that the preereqs are loaded // prior to any RPC calls being made. // // https://github.com/dotnet/roslyn/issues/29602 will track removing this hack // since that's the primary offending persister that needs to be addressed. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _ = GetCapabilities(new VSClientCapabilities { SupportsVisualStudioExtensions = true }); if (_languageServer is not null) { Contract.ThrowIfFalse(_languageServer.HasShutdownStarted, "The language server has not yet been asked to shutdown."); await _languageServer.DisposeAsync().ConfigureAwait(false); } var (clientStream, serverStream) = FullDuplexStream.CreatePair(); _languageServer = (LanguageServerTarget)await CreateAsync( this, serverStream, serverStream, _lspWorkspaceRegistrationService, _asyncServiceProvider, _diagnosticsClientName, cancellationToken).ConfigureAwait(false); return new Connection(clientStream, clientStream); } /// <summary> /// Signals that the extension has been loaded. The server can be started immediately, or wait for user action to start. /// To start the server, invoke the <see cref="StartAsync"/> event; /// </summary> public async Task OnLoadedAsync() { await StartAsync.InvokeAsync(this, EventArgs.Empty).ConfigureAwait(false); } /// <summary> /// Signals the extension that the language server has been successfully initialized. /// </summary> /// <returns>A <see cref="Task"/> which completes when actions that need to be performed when the server is ready are done.</returns> public Task OnServerInitializedAsync() { // We don't have any tasks that need to be triggered after the server has successfully initialized. return Task.CompletedTask; } /// <summary> /// Signals the extension that the language server failed to initialize. /// </summary> /// <returns>A <see cref="Task"/> which completes when additional actions that need to be performed when the server fails to initialize are done.</returns> public Task OnServerInitializeFailedAsync(Exception e) { // We don't need to provide additional exception handling here, liveshare already handles failure cases for this server. return Task.CompletedTask; } internal static async Task<ILanguageServerTarget> CreateAsync( AbstractInProcLanguageClient languageClient, Stream inputStream, Stream outputStream, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, VSShell.IAsyncServiceProvider? asyncServiceProvider, string? clientName, CancellationToken cancellationToken) { var jsonMessageFormatter = new JsonMessageFormatter(); VSExtensionUtilities.AddVSExtensionConverters(jsonMessageFormatter.JsonSerializer); var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream, jsonMessageFormatter)) { ExceptionStrategy = ExceptionProcessing.ISerializable, }; var serverTypeName = languageClient.GetType().Name; var logger = await CreateLoggerAsync(asyncServiceProvider, serverTypeName, clientName, jsonRpc, cancellationToken).ConfigureAwait(false); var server = languageClient.Create( jsonRpc, languageClient, lspWorkspaceRegistrationService, logger ?? NoOpLspLogger.Instance); jsonRpc.StartListening(); return server; } private static async Task<LogHubLspLogger?> CreateLoggerAsync( VSShell.IAsyncServiceProvider? asyncServiceProvider, string serverTypeName, string? clientName, JsonRpc jsonRpc, CancellationToken cancellationToken) { if (asyncServiceProvider == null) return null; var logName = $"Roslyn.{serverTypeName}.{clientName ?? "Default"}.{Interlocked.Increment(ref s_logHubSessionId)}"; var logId = new LogId(logName, new ServiceMoniker(typeof(LanguageServerTarget).FullName)); var serviceContainer = await VSShell.ServiceExtensions.GetServiceAsync<SVsBrokeredServiceContainer, IBrokeredServiceContainer>(asyncServiceProvider).ConfigureAwait(false); var service = serviceContainer.GetFullAccessServiceBroker(); var configuration = await TraceConfiguration.CreateTraceConfigurationInstanceAsync(service, cancellationToken).ConfigureAwait(false); var logOptions = new RpcContracts.Logging.LoggerOptions(new LoggingLevelSettings(SourceLevels.ActivityTracing | SourceLevels.Information)); var traceSource = await configuration.RegisterLogSourceAsync(logId, logOptions, cancellationToken).ConfigureAwait(false); // Associate this trace source with the jsonrpc conduit. This ensures that we can associate logs we report // with our callers and the operations they are performing. jsonRpc.ActivityTracingStrategy = new CorrelationManagerTracingStrategy { TraceSource = traceSource }; return new LogHubLspLogger(configuration, traceSource); } public ILanguageServerTarget Create( JsonRpc jsonRpc, ICapabilitiesProvider capabilitiesProvider, ILspWorkspaceRegistrationService workspaceRegistrationService, ILspLogger logger) { return new VisualStudioInProcLanguageServer( _requestDispatcherFactory, jsonRpc, capabilitiesProvider, workspaceRegistrationService, _listenerProvider, logger, _diagnosticService, clientName: _diagnosticsClientName, userVisibleServerName: this.Name, telemetryServerTypeName: this.GetType().Name); } public abstract ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Threading; using Nerdbank.Streams; using Roslyn.Utilities; using StreamJsonRpc; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { internal abstract partial class AbstractInProcLanguageClient : ILanguageClient, ILanguageServerFactory, ICapabilitiesProvider { private readonly string? _diagnosticsClientName; private readonly IThreadingContext _threadingContext; private readonly ILspLoggerFactory _lspLoggerFactory; /// <summary> /// Legacy support for LSP push diagnostics. /// </summary> private readonly IDiagnosticService? _diagnosticService; private readonly IAsynchronousOperationListenerProvider _listenerProvider; private readonly AbstractRequestDispatcherFactory _requestDispatcherFactory; private readonly ILspWorkspaceRegistrationService _lspWorkspaceRegistrationService; protected readonly Workspace Workspace; /// <summary> /// Created when <see cref="ActivateAsync"/> is called. /// </summary> private LanguageServerTarget? _languageServer; /// <summary> /// Gets the name of the language client (displayed to the user). /// </summary> public abstract string Name { get; } /// <summary> /// Unused, implementing <see cref="ILanguageClient"/> /// No additional settings are provided for this server, so we do not need any configuration section names. /// </summary> public IEnumerable<string>? ConfigurationSections { get; } /// <summary> /// Gets the initialization options object the client wants to send when 'initialize' message is sent. /// See https://microsoft.github.io/language-server-protocol/specifications/specification-3-14/#initialize /// We do not provide any additional initialization options. /// </summary> public object? InitializationOptions { get; } /// <summary> /// Unused, implementing <see cref="ILanguageClient"/> /// Files that we care about are already provided and watched by the workspace. /// </summary> public IEnumerable<string>? FilesToWatch { get; } public event AsyncEventHandler<EventArgs>? StartAsync; /// <summary> /// Unused, implementing <see cref="ILanguageClient"/> /// </summary> public event AsyncEventHandler<EventArgs>? StopAsync { add { } remove { } } public AbstractInProcLanguageClient( AbstractRequestDispatcherFactory requestDispatcherFactory, VisualStudioWorkspace workspace, IDiagnosticService? diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, ILspLoggerFactory lspLoggerFactory, IThreadingContext threadingContext, string? diagnosticsClientName) { _requestDispatcherFactory = requestDispatcherFactory; Workspace = workspace; _diagnosticService = diagnosticService; _listenerProvider = listenerProvider; _lspWorkspaceRegistrationService = lspWorkspaceRegistrationService; _diagnosticsClientName = diagnosticsClientName; _lspLoggerFactory = lspLoggerFactory; _threadingContext = threadingContext; } public async Task<Connection?> ActivateAsync(CancellationToken cancellationToken) { // HACK HACK HACK: prevent potential crashes/state corruption during load. Fixes // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1261421 // // When we create an LSP server, we compute our server capabilities; this may depend on // reading things like workspace options which will force us to initialize our option persisters. // Unfortunately some of our option persisters currently assert they are first created on the UI // thread. If the first time they're created is because of LSP initialization, we might end up loading // them on a background thread which will throw exceptions and then prevent them from being created // again later. // // The correct fix for this is to fix the threading violations in the option persister code; // asserting a MEF component is constructed on the foreground thread is never allowed, but alas it's // done there. Fixing that isn't difficult but comes with some risk I don't want to take for 16.9; // instead we'll just compute our capabilities here on the UI thread to ensure everything is loaded. // We _could_ consider doing a SwitchToMainThreadAsync in InProcLanguageServer.InitializeAsync // (where the problematic call to GetCapabilites is), but that call is invoked across the StreamJsonRpc // link where it's unclear if VS Threading rules apply. By doing this here, we are dong it in a // VS API that is following VS Threading rules, and it also ensures that the preereqs are loaded // prior to any RPC calls being made. // // https://github.com/dotnet/roslyn/issues/29602 will track removing this hack // since that's the primary offending persister that needs to be addressed. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _ = GetCapabilities(new VSClientCapabilities { SupportsVisualStudioExtensions = true }); if (_languageServer is not null) { Contract.ThrowIfFalse(_languageServer.HasShutdownStarted, "The language server has not yet been asked to shutdown."); await _languageServer.DisposeAsync().ConfigureAwait(false); } var (clientStream, serverStream) = FullDuplexStream.CreatePair(); _languageServer = (LanguageServerTarget)await CreateAsync( this, serverStream, serverStream, _lspWorkspaceRegistrationService, _lspLoggerFactory, _diagnosticsClientName, cancellationToken).ConfigureAwait(false); return new Connection(clientStream, clientStream); } /// <summary> /// Signals that the extension has been loaded. The server can be started immediately, or wait for user action to start. /// To start the server, invoke the <see cref="StartAsync"/> event; /// </summary> public async Task OnLoadedAsync() { await StartAsync.InvokeAsync(this, EventArgs.Empty).ConfigureAwait(false); } /// <summary> /// Signals the extension that the language server has been successfully initialized. /// </summary> /// <returns>A <see cref="Task"/> which completes when actions that need to be performed when the server is ready are done.</returns> public Task OnServerInitializedAsync() { // We don't have any tasks that need to be triggered after the server has successfully initialized. return Task.CompletedTask; } /// <summary> /// Signals the extension that the language server failed to initialize. /// </summary> /// <returns>A <see cref="Task"/> which completes when additional actions that need to be performed when the server fails to initialize are done.</returns> public Task OnServerInitializeFailedAsync(Exception e) { // We don't need to provide additional exception handling here, liveshare already handles failure cases for this server. return Task.CompletedTask; } internal static async Task<ILanguageServerTarget> CreateAsync( AbstractInProcLanguageClient languageClient, Stream inputStream, Stream outputStream, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, ILspLoggerFactory lspLoggerFactory, string? clientName, CancellationToken cancellationToken) { var jsonMessageFormatter = new JsonMessageFormatter(); VSExtensionUtilities.AddVSExtensionConverters(jsonMessageFormatter.JsonSerializer); var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream, jsonMessageFormatter)) { ExceptionStrategy = ExceptionProcessing.ISerializable, }; var serverTypeName = languageClient.GetType().Name; var logger = await lspLoggerFactory.CreateLoggerAsync(serverTypeName, clientName, jsonRpc, cancellationToken).ConfigureAwait(false); var server = languageClient.Create( jsonRpc, languageClient, lspWorkspaceRegistrationService, logger); jsonRpc.StartListening(); return server; } public ILanguageServerTarget Create( JsonRpc jsonRpc, ICapabilitiesProvider capabilitiesProvider, ILspWorkspaceRegistrationService workspaceRegistrationService, ILspLogger logger) { return new VisualStudioInProcLanguageServer( _requestDispatcherFactory, jsonRpc, capabilitiesProvider, workspaceRegistrationService, _listenerProvider, logger, _diagnosticService, clientName: _diagnosticsClientName, userVisibleServerName: this.Name, telemetryServerTypeName: this.GetType().Name); } public abstract ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities); } }
1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Def/Implementation/LanguageClient/AlwaysActivateInProcLanguageClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; using VSShell = Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { /// <summary> /// Language client responsible for handling C# / VB / F# LSP requests in any scenario (both local and codespaces). /// This powers "LSP only" features (e.g. cntrl+Q code search) that do not use traditional editor APIs. /// It is always activated whenever roslyn is activated. /// </summary> [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [ContentType(ContentTypeNames.FSharpContentType)] [Export(typeof(ILanguageClient))] [Export(typeof(AlwaysActivateInProcLanguageClient))] internal class AlwaysActivateInProcLanguageClient : AbstractInProcLanguageClient { private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public AlwaysActivateInProcLanguageClient( RequestDispatcherFactory csharpVBRequestDispatcherFactory, VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, DefaultCapabilitiesProvider defaultCapabilitiesProvider, [Import(typeof(SAsyncServiceProvider))] VSShell.IAsyncServiceProvider asyncServiceProvider, IThreadingContext threadingContext) : base(csharpVBRequestDispatcherFactory, workspace, diagnosticService: null, listenerProvider, lspWorkspaceRegistrationService, asyncServiceProvider, threadingContext, diagnosticsClientName: null) { _defaultCapabilitiesProvider = defaultCapabilitiesProvider; } public override string Name => CSharpVisualBasicLanguageServerFactory.UserVisibleName; public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var serverCapabilities = new VSServerCapabilities(); // If the LSP editor feature flag is enabled advertise support for LSP features here so they are available locally and remote. var isLspEditorEnabled = Workspace.Services.GetRequiredService<IExperimentationService>().IsExperimentEnabled(VisualStudioWorkspaceContextService.LspEditorFeatureFlagName); if (isLspEditorEnabled) { serverCapabilities = (VSServerCapabilities)_defaultCapabilitiesProvider.GetCapabilities(clientCapabilities); } else { // Even if the flag is off, we want to include text sync capabilities. serverCapabilities.TextDocumentSync = new TextDocumentSyncOptions { Change = TextDocumentSyncKind.Incremental, OpenClose = true, }; } serverCapabilities.SupportsDiagnosticRequests = Workspace.IsPullDiagnostics(InternalDiagnosticsOptions.NormalDiagnosticMode); // This capability is always enabled as we provide cntrl+Q VS search only via LSP in ever scenario. serverCapabilities.WorkspaceSymbolProvider = true; // This capability prevents NavigateTo (cntrl+,) from using LSP symbol search when the server also supports WorkspaceSymbolProvider. // Since WorkspaceSymbolProvider=true always to allow cntrl+Q VS search to function, we set DisableGoToWorkspaceSymbols=true // when not running the experimental LSP editor. This ensures NavigateTo uses the existing editor APIs. // However, when the experimental LSP editor is enabled we want LSP to power NavigateTo, so we set DisableGoToWorkspaceSymbols=false. serverCapabilities.DisableGoToWorkspaceSymbols = !isLspEditorEnabled; return serverCapabilities; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { /// <summary> /// Language client responsible for handling C# / VB / F# LSP requests in any scenario (both local and codespaces). /// This powers "LSP only" features (e.g. cntrl+Q code search) that do not use traditional editor APIs. /// It is always activated whenever roslyn is activated. /// </summary> [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [ContentType(ContentTypeNames.FSharpContentType)] [Export(typeof(ILanguageClient))] [Export(typeof(AlwaysActivateInProcLanguageClient))] internal class AlwaysActivateInProcLanguageClient : AbstractInProcLanguageClient { private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public AlwaysActivateInProcLanguageClient( RequestDispatcherFactory csharpVBRequestDispatcherFactory, VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, DefaultCapabilitiesProvider defaultCapabilitiesProvider, ILspLoggerFactory lspLoggerFactory, IThreadingContext threadingContext) : base(csharpVBRequestDispatcherFactory, workspace, diagnosticService: null, listenerProvider, lspWorkspaceRegistrationService, lspLoggerFactory, threadingContext, diagnosticsClientName: null) { _defaultCapabilitiesProvider = defaultCapabilitiesProvider; } public override string Name => CSharpVisualBasicLanguageServerFactory.UserVisibleName; public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var serverCapabilities = new VSServerCapabilities(); // If the LSP editor feature flag is enabled advertise support for LSP features here so they are available locally and remote. var isLspEditorEnabled = Workspace.Services.GetRequiredService<IExperimentationService>().IsExperimentEnabled(VisualStudioWorkspaceContextService.LspEditorFeatureFlagName); if (isLspEditorEnabled) { serverCapabilities = (VSServerCapabilities)_defaultCapabilitiesProvider.GetCapabilities(clientCapabilities); } else { // Even if the flag is off, we want to include text sync capabilities. serverCapabilities.TextDocumentSync = new TextDocumentSyncOptions { Change = TextDocumentSyncKind.Incremental, OpenClose = true, }; } serverCapabilities.SupportsDiagnosticRequests = Workspace.IsPullDiagnostics(InternalDiagnosticsOptions.NormalDiagnosticMode); // This capability is always enabled as we provide cntrl+Q VS search only via LSP in ever scenario. serverCapabilities.WorkspaceSymbolProvider = true; // This capability prevents NavigateTo (cntrl+,) from using LSP symbol search when the server also supports WorkspaceSymbolProvider. // Since WorkspaceSymbolProvider=true always to allow cntrl+Q VS search to function, we set DisableGoToWorkspaceSymbols=true // when not running the experimental LSP editor. This ensures NavigateTo uses the existing editor APIs. // However, when the experimental LSP editor is enabled we want LSP to power NavigateTo, so we set DisableGoToWorkspaceSymbols=false. serverCapabilities.DisableGoToWorkspaceSymbols = !isLspEditorEnabled; return serverCapabilities; } } }
1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Def/Implementation/LanguageClient/LiveShareInProcLanguageClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; using VSShell = Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { // The C# and VB ILanguageClient should not activate on the host. When LiveShare mirrors the C# ILC to the guest, // they will not copy the DisableUserExperience attribute, so guests will still use the C# ILC. [DisableUserExperience(true)] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [Export(typeof(ILanguageClient))] internal class LiveShareInProcLanguageClient : AbstractInProcLanguageClient { private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public LiveShareInProcLanguageClient( RequestDispatcherFactory csharpVBRequestDispatcherFactory, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, DefaultCapabilitiesProvider defaultCapabilitiesProvider, [Import(typeof(SAsyncServiceProvider))] VSShell.IAsyncServiceProvider asyncServiceProvider, IThreadingContext threadingContext) : base(csharpVBRequestDispatcherFactory, workspace, diagnosticService, listenerProvider, lspWorkspaceRegistrationService, asyncServiceProvider, threadingContext, diagnosticsClientName: null) { _defaultCapabilitiesProvider = defaultCapabilitiesProvider; } public override string Name => "Live Share C#/Visual Basic Language Server Client"; public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var experimentationService = Workspace.Services.GetRequiredService<IExperimentationService>(); var isLspEditorEnabled = experimentationService.IsExperimentEnabled(VisualStudioWorkspaceContextService.LspEditorFeatureFlagName); // If the preview feature flag to turn on the LSP editor in local scenarios is on, advertise no capabilities for this Live Share // LSP server as LSP requests will be serviced by the AlwaysActiveInProcLanguageClient in both local and remote scenarios. if (isLspEditorEnabled) { return new VSServerCapabilities { TextDocumentSync = new TextDocumentSyncOptions { OpenClose = false, Change = TextDocumentSyncKind.None, } }; } return _defaultCapabilitiesProvider.GetCapabilities(clientCapabilities); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { // The C# and VB ILanguageClient should not activate on the host. When LiveShare mirrors the C# ILC to the guest, // they will not copy the DisableUserExperience attribute, so guests will still use the C# ILC. [DisableUserExperience(true)] [ContentType(ContentTypeNames.CSharpContentType)] [ContentType(ContentTypeNames.VisualBasicContentType)] [Export(typeof(ILanguageClient))] internal class LiveShareInProcLanguageClient : AbstractInProcLanguageClient { private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public LiveShareInProcLanguageClient( RequestDispatcherFactory csharpVBRequestDispatcherFactory, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, DefaultCapabilitiesProvider defaultCapabilitiesProvider, ILspLoggerFactory lspLoggerFactory, IThreadingContext threadingContext) : base(csharpVBRequestDispatcherFactory, workspace, diagnosticService, listenerProvider, lspWorkspaceRegistrationService, lspLoggerFactory, threadingContext, diagnosticsClientName: null) { _defaultCapabilitiesProvider = defaultCapabilitiesProvider; } public override string Name => "Live Share C#/Visual Basic Language Server Client"; public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var experimentationService = Workspace.Services.GetRequiredService<IExperimentationService>(); var isLspEditorEnabled = experimentationService.IsExperimentEnabled(VisualStudioWorkspaceContextService.LspEditorFeatureFlagName); // If the preview feature flag to turn on the LSP editor in local scenarios is on, advertise no capabilities for this Live Share // LSP server as LSP requests will be serviced by the AlwaysActiveInProcLanguageClient in both local and remote scenarios. if (isLspEditorEnabled) { return new VSServerCapabilities { TextDocumentSync = new TextDocumentSyncOptions { OpenClose = false, Change = TextDocumentSyncKind.None, } }; } return _defaultCapabilitiesProvider.GetCapabilities(clientCapabilities); } } }
1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Def/Implementation/LanguageClient/LogHubLspLogger.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 Microsoft.CodeAnalysis.LanguageServer; using Microsoft.VisualStudio.LogHub; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { internal abstract partial class AbstractInProcLanguageClient { private class LogHubLspLogger : ILspLogger { private readonly TraceConfiguration _configuration; private readonly TraceSource _traceSource; private bool _disposed; public LogHubLspLogger(TraceConfiguration configuration, TraceSource traceSource) { _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _traceSource = traceSource ?? throw new ArgumentNullException(nameof(traceSource)); } public void Dispose() { if (_disposed) { Contract.Fail($"{GetType().FullName} was double disposed"); return; } _disposed = true; _traceSource.Flush(); _traceSource.Close(); _configuration.Dispose(); } public void TraceInformation(string message) => _traceSource.TraceInformation(message); public void TraceWarning(string message) => _traceSource.TraceEvent(TraceEventType.Warning, id: 0, message); public void TraceException(Exception exception) => _traceSource.TraceEvent(TraceEventType.Error, id: 0, "Exception: {0}", exception); public void TraceStart(string message) => _traceSource.TraceEvent(TraceEventType.Start, id: 0, message); public void TraceStop(string message) => _traceSource.TraceEvent(TraceEventType.Stop, id: 0, message); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.LanguageServer; using Microsoft.VisualStudio.LogHub; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { internal class LogHubLspLogger : ILspLogger { private readonly TraceConfiguration _configuration; private readonly TraceSource _traceSource; private bool _disposed; public LogHubLspLogger(TraceConfiguration configuration, TraceSource traceSource) { _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _traceSource = traceSource ?? throw new ArgumentNullException(nameof(traceSource)); } public void Dispose() { if (_disposed) { Contract.Fail($"{GetType().FullName} was double disposed"); return; } _disposed = true; _traceSource.Flush(); _traceSource.Close(); _configuration.Dispose(); } public void TraceInformation(string message) => _traceSource.TraceInformation(message); public void TraceWarning(string message) => _traceSource.TraceEvent(TraceEventType.Warning, id: 0, message); public void TraceException(Exception exception) => _traceSource.TraceEvent(TraceEventType.Error, id: 0, "Exception: {0}", exception); public void TraceStart(string message) => _traceSource.TraceEvent(TraceEventType.Start, id: 0, message); public void TraceStop(string message) => _traceSource.TraceEvent(TraceEventType.Stop, id: 0, message); } }
1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Def/Implementation/LanguageClient/RazorInProcLanguageClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; using VSShell = Microsoft.VisualStudio.Shell; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Lsp { /// <summary> /// Defines the LSP server for Razor C#. This is separate so that we can /// activate this outside of a liveshare session and publish diagnostics /// only for razor cs files. /// TODO - This can be removed once C# is using LSP for diagnostics. /// https://github.com/dotnet/roslyn/issues/42630 /// </summary> /// <remarks> /// This specifies RunOnHost because in LiveShare we don't want this to activate on the guest instance /// because LiveShare drops the ClientName when it mirrors guest clients, so this client ends up being /// activated solely by its content type, which means it receives requests for normal .cs and .vb files /// even for non-razor projects, which then of course fails because it gets text sync info for documents /// it doesn't know about. /// </remarks> [ContentType(ContentTypeNames.CSharpContentType)] [ClientName(ClientName)] [RunOnContext(RunningContext.RunOnHost)] [Export(typeof(ILanguageClient))] internal class RazorInProcLanguageClient : AbstractInProcLanguageClient { public const string ClientName = ProtocolConstants.RazorCSharp; private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider; /// <summary> /// Gets the name of the language client (displayed in yellow bars). /// </summary> public override string Name => "Razor C# Language Server Client"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RazorInProcLanguageClient( RequestDispatcherFactory csharpVBRequestDispatcherFactory, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, DefaultCapabilitiesProvider defaultCapabilitiesProvider, IThreadingContext threadingContext, [Import(typeof(SAsyncServiceProvider))] VSShell.IAsyncServiceProvider asyncServiceProvider) : base(csharpVBRequestDispatcherFactory, workspace, diagnosticService, listenerProvider, lspWorkspaceRegistrationService, asyncServiceProvider, threadingContext, ClientName) { _defaultCapabilitiesProvider = defaultCapabilitiesProvider; } public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var capabilities = _defaultCapabilitiesProvider.GetCapabilities(clientCapabilities); // Razor doesn't use workspace symbols, so disable to prevent duplicate results (with LiveshareLanguageClient) in liveshare. capabilities.WorkspaceSymbolProvider = false; if (capabilities is VSServerCapabilities vsServerCapabilities) { vsServerCapabilities.SupportsDiagnosticRequests = this.Workspace.IsPullDiagnostics(InternalDiagnosticsOptions.RazorDiagnosticMode); return vsServerCapabilities; } return capabilities; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Lsp { /// <summary> /// Defines the LSP server for Razor C#. This is separate so that we can /// activate this outside of a liveshare session and publish diagnostics /// only for razor cs files. /// TODO - This can be removed once C# is using LSP for diagnostics. /// https://github.com/dotnet/roslyn/issues/42630 /// </summary> /// <remarks> /// This specifies RunOnHost because in LiveShare we don't want this to activate on the guest instance /// because LiveShare drops the ClientName when it mirrors guest clients, so this client ends up being /// activated solely by its content type, which means it receives requests for normal .cs and .vb files /// even for non-razor projects, which then of course fails because it gets text sync info for documents /// it doesn't know about. /// </remarks> [ContentType(ContentTypeNames.CSharpContentType)] [ClientName(ClientName)] [RunOnContext(RunningContext.RunOnHost)] [Export(typeof(ILanguageClient))] internal class RazorInProcLanguageClient : AbstractInProcLanguageClient { public const string ClientName = ProtocolConstants.RazorCSharp; private readonly DefaultCapabilitiesProvider _defaultCapabilitiesProvider; /// <summary> /// Gets the name of the language client (displayed in yellow bars). /// </summary> public override string Name => "Razor C# Language Server Client"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RazorInProcLanguageClient( RequestDispatcherFactory csharpVBRequestDispatcherFactory, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, DefaultCapabilitiesProvider defaultCapabilitiesProvider, IThreadingContext threadingContext, ILspLoggerFactory lspLoggerFactory) : base(csharpVBRequestDispatcherFactory, workspace, diagnosticService, listenerProvider, lspWorkspaceRegistrationService, lspLoggerFactory, threadingContext, ClientName) { _defaultCapabilitiesProvider = defaultCapabilitiesProvider; } public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var capabilities = _defaultCapabilitiesProvider.GetCapabilities(clientCapabilities); // Razor doesn't use workspace symbols, so disable to prevent duplicate results (with LiveshareLanguageClient) in liveshare. capabilities.WorkspaceSymbolProvider = false; if (capabilities is VSServerCapabilities vsServerCapabilities) { vsServerCapabilities.SupportsDiagnosticRequests = this.Workspace.IsPullDiagnostics(InternalDiagnosticsOptions.RazorDiagnosticMode); return vsServerCapabilities; } return capabilities; } } }
1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; using VSShell = Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Xaml { /// <summary> /// Experimental XAML Language Server Client used everywhere when /// <see cref="StringConstants.EnableLspIntelliSense"/> experiment is turned on. /// </summary> [ContentType(ContentTypeNames.XamlContentType)] [Export(typeof(ILanguageClient))] internal class XamlInProcLanguageClient : AbstractInProcLanguageClient { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public XamlInProcLanguageClient( XamlRequestDispatcherFactory xamlDispatcherFactory, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, [Import(typeof(SAsyncServiceProvider))] VSShell.IAsyncServiceProvider asyncServiceProvider, IThreadingContext threadingContext) : base(xamlDispatcherFactory, workspace, diagnosticService, listenerProvider, lspWorkspaceRegistrationService, asyncServiceProvider, threadingContext, diagnosticsClientName: null) { } /// <summary> /// Gets the name of the language client (displayed in yellow bars). /// When updating the string of Name, please make sure to update the same string in Microsoft.VisualStudio.LanguageServer.Client.ExperimentalSnippetSupport.AllowList /// </summary> public override string Name => "XAML Language Server Client (Experimental)"; public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var experimentationService = Workspace.Services.GetRequiredService<IExperimentationService>(); var isLspExperimentEnabled = experimentationService.IsExperimentEnabled(StringConstants.EnableLspIntelliSense); return isLspExperimentEnabled ? XamlCapabilities.Current : XamlCapabilities.None; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml { /// <summary> /// Experimental XAML Language Server Client used everywhere when /// <see cref="StringConstants.EnableLspIntelliSense"/> experiment is turned on. /// </summary> [ContentType(ContentTypeNames.XamlContentType)] [Export(typeof(ILanguageClient))] internal class XamlInProcLanguageClient : AbstractInProcLanguageClient { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public XamlInProcLanguageClient( XamlRequestDispatcherFactory xamlDispatcherFactory, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, ILspLoggerFactory lspLoggerFactory, IThreadingContext threadingContext) : base(xamlDispatcherFactory, workspace, diagnosticService, listenerProvider, lspWorkspaceRegistrationService, lspLoggerFactory, threadingContext, diagnosticsClientName: null) { } /// <summary> /// Gets the name of the language client (displayed in yellow bars). /// When updating the string of Name, please make sure to update the same string in Microsoft.VisualStudio.LanguageServer.Client.ExperimentalSnippetSupport.AllowList /// </summary> public override string Name => "XAML Language Server Client (Experimental)"; public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var experimentationService = Workspace.Services.GetRequiredService<IExperimentationService>(); var isLspExperimentEnabled = experimentationService.IsExperimentEnabled(StringConstants.EnableLspIntelliSense); return isLspExperimentEnabled ? XamlCapabilities.Current : XamlCapabilities.None; } } }
1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlInProcLanguageClientDisableUX.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; using VSShell = Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Xaml { /// <summary> /// XAML Language Server Client for LiveShare and Codespaces. Unused when /// <see cref="StringConstants.EnableLspIntelliSense"/> experiment is turned on. /// Remove this when we are ready to use LSP everywhere /// </summary> [DisableUserExperience(true)] [ContentType(ContentTypeNames.XamlContentType)] [Export(typeof(ILanguageClient))] internal class XamlInProcLanguageClientDisableUX : AbstractInProcLanguageClient { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public XamlInProcLanguageClientDisableUX( XamlRequestDispatcherFactory xamlDispatcherFactory, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, [Import(typeof(SAsyncServiceProvider))] VSShell.IAsyncServiceProvider asyncServiceProvider, IThreadingContext threadingContext) : base(xamlDispatcherFactory, workspace, diagnosticService, listenerProvider, lspWorkspaceRegistrationService, asyncServiceProvider, threadingContext, diagnosticsClientName: null) { } /// <summary> /// Gets the name of the language client (displayed in yellow bars). /// </summary> public override string Name => "XAML Language Server Client for LiveShare and Codespaces"; public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var experimentationService = Workspace.Services.GetRequiredService<IExperimentationService>(); var isLspExperimentEnabled = experimentationService.IsExperimentEnabled(StringConstants.EnableLspIntelliSense); var capabilities = isLspExperimentEnabled ? XamlCapabilities.None : XamlCapabilities.Current; // Only turn on CodeAction support for client scenarios. Hosts will get non-LSP lightbulbs automatically. capabilities.CodeActionProvider = new CodeActionOptions { CodeActionKinds = new[] { CodeActionKind.QuickFix, CodeActionKind.Refactor } }; capabilities.CodeActionsResolveProvider = true; return capabilities; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Xaml { /// <summary> /// XAML Language Server Client for LiveShare and Codespaces. Unused when /// <see cref="StringConstants.EnableLspIntelliSense"/> experiment is turned on. /// Remove this when we are ready to use LSP everywhere /// </summary> [DisableUserExperience(true)] [ContentType(ContentTypeNames.XamlContentType)] [Export(typeof(ILanguageClient))] internal class XamlInProcLanguageClientDisableUX : AbstractInProcLanguageClient { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public XamlInProcLanguageClientDisableUX( XamlRequestDispatcherFactory xamlDispatcherFactory, VisualStudioWorkspace workspace, IDiagnosticService diagnosticService, IAsynchronousOperationListenerProvider listenerProvider, ILspWorkspaceRegistrationService lspWorkspaceRegistrationService, ILspLoggerFactory lspLoggerFactory, IThreadingContext threadingContext) : base(xamlDispatcherFactory, workspace, diagnosticService, listenerProvider, lspWorkspaceRegistrationService, lspLoggerFactory, threadingContext, diagnosticsClientName: null) { } /// <summary> /// Gets the name of the language client (displayed in yellow bars). /// </summary> public override string Name => "XAML Language Server Client for LiveShare and Codespaces"; public override ServerCapabilities GetCapabilities(ClientCapabilities clientCapabilities) { var experimentationService = Workspace.Services.GetRequiredService<IExperimentationService>(); var isLspExperimentEnabled = experimentationService.IsExperimentEnabled(StringConstants.EnableLspIntelliSense); var capabilities = isLspExperimentEnabled ? XamlCapabilities.None : XamlCapabilities.Current; // Only turn on CodeAction support for client scenarios. Hosts will get non-LSP lightbulbs automatically. capabilities.CodeActionProvider = new CodeActionOptions { CodeActionKinds = new[] { CodeActionKind.QuickFix, CodeActionKind.Refactor } }; capabilities.CodeActionsResolveProvider = true; return capabilities; } } }
1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/Core/Portable/InternalUtilities/StreamExtensions.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.IO; namespace Roslyn.Utilities { internal static class StreamExtensions { /// <summary> /// Attempts to read all of the requested bytes from the stream into the buffer /// </summary> /// <returns> /// The number of bytes read. Less than <paramref name="count" /> will /// only be returned if the end of stream is reached before all bytes can be read. /// </returns> /// <remarks> /// Unlike <see cref="Stream.Read(byte[], int, int)"/> it is not guaranteed that /// the stream position or the output buffer will be unchanged if an exception is /// returned. /// </remarks> public static int TryReadAll( this Stream stream, byte[] buffer, int offset, int count) { // The implementations for many streams, e.g. FileStream, allows 0 bytes to be // read and returns 0, but the documentation for Stream.Read states that 0 is // only returned when the end of the stream has been reached. Rather than deal // with this contradiction, let's just never pass a count of 0 bytes Debug.Assert(count > 0); int totalBytesRead; int bytesRead; for (totalBytesRead = 0; totalBytesRead < count; totalBytesRead += bytesRead) { // Note: Don't attempt to save state in-between calls to .Read as it would // require a possibly massive intermediate buffer array bytesRead = stream.Read(buffer, offset + totalBytesRead, count - totalBytesRead); if (bytesRead == 0) { break; } } return totalBytesRead; } /// <summary> /// Reads all bytes from the current position of the given stream to its end. /// </summary> public static byte[] ReadAllBytes(this Stream stream) { if (stream.CanSeek) { long length = stream.Length - stream.Position; if (length == 0) { return Array.Empty<byte>(); } var buffer = new byte[length]; int actualLength = TryReadAll(stream, buffer, 0, buffer.Length); Array.Resize(ref buffer, actualLength); return buffer; } var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); return memoryStream.ToArray(); } } }
// Licensed to the .NET Foundation under one or more 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.IO; namespace Roslyn.Utilities { internal static class StreamExtensions { /// <summary> /// Attempts to read all of the requested bytes from the stream into the buffer /// </summary> /// <returns> /// The number of bytes read. Less than <paramref name="count" /> will /// only be returned if the end of stream is reached before all bytes can be read. /// </returns> /// <remarks> /// Unlike <see cref="Stream.Read(byte[], int, int)"/> it is not guaranteed that /// the stream position or the output buffer will be unchanged if an exception is /// returned. /// </remarks> public static int TryReadAll( this Stream stream, byte[] buffer, int offset, int count) { // The implementations for many streams, e.g. FileStream, allows 0 bytes to be // read and returns 0, but the documentation for Stream.Read states that 0 is // only returned when the end of the stream has been reached. Rather than deal // with this contradiction, let's just never pass a count of 0 bytes Debug.Assert(count > 0); int totalBytesRead; int bytesRead; for (totalBytesRead = 0; totalBytesRead < count; totalBytesRead += bytesRead) { // Note: Don't attempt to save state in-between calls to .Read as it would // require a possibly massive intermediate buffer array bytesRead = stream.Read(buffer, offset + totalBytesRead, count - totalBytesRead); if (bytesRead == 0) { break; } } return totalBytesRead; } /// <summary> /// Reads all bytes from the current position of the given stream to its end. /// </summary> public static byte[] ReadAllBytes(this Stream stream) { if (stream.CanSeek) { long length = stream.Length - stream.Position; if (length == 0) { return Array.Empty<byte>(); } var buffer = new byte[length]; int actualLength = TryReadAll(stream, buffer, 0, buffer.Length); Array.Resize(ref buffer, actualLength); return buffer; } var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); return memoryStream.ToArray(); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Analyzers/CSharp/Analyzers/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UseInferredMemberName; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseInferredMemberName { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUseInferredMemberNameDiagnosticAnalyzer : AbstractUseInferredMemberNameDiagnosticAnalyzer { protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.NameColon, SyntaxKind.NameEquals); protected override void LanguageSpecificAnalyzeSyntax(SyntaxNodeAnalysisContext context, SyntaxTree syntaxTree, AnalyzerOptions options, CancellationToken cancellationToken) { switch (context.Node.Kind()) { case SyntaxKind.NameColon: ReportDiagnosticsIfNeeded((NameColonSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; case SyntaxKind.NameEquals: ReportDiagnosticsIfNeeded((NameEqualsSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; } } private void ReportDiagnosticsIfNeeded(NameColonSyntax nameColon, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameColon.Parent.IsKind(SyntaxKind.Argument, out ArgumentSyntax? argument)) { return; } var parseOptions = (CSharpParseOptions)syntaxTree.Options; var preference = options.GetOption( CodeStyleOptions2.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyTupleElementName(argument, parseOptions)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameColon.Name.SpanStart, nameColon.ColonToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameColon.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } private void ReportDiagnosticsIfNeeded(NameEqualsSyntax nameEquals, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameEquals.Parent.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonCtor)) { return; } var preference = options.GetOption( CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyAnonymousTypeMemberName(anonCtor)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameEquals.Name.SpanStart, nameEquals.EqualsToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameEquals.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UseInferredMemberName; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseInferredMemberName { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUseInferredMemberNameDiagnosticAnalyzer : AbstractUseInferredMemberNameDiagnosticAnalyzer { protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.NameColon, SyntaxKind.NameEquals); protected override void LanguageSpecificAnalyzeSyntax(SyntaxNodeAnalysisContext context, SyntaxTree syntaxTree, AnalyzerOptions options, CancellationToken cancellationToken) { switch (context.Node.Kind()) { case SyntaxKind.NameColon: ReportDiagnosticsIfNeeded((NameColonSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; case SyntaxKind.NameEquals: ReportDiagnosticsIfNeeded((NameEqualsSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; } } private void ReportDiagnosticsIfNeeded(NameColonSyntax nameColon, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameColon.Parent.IsKind(SyntaxKind.Argument, out ArgumentSyntax? argument)) { return; } var parseOptions = (CSharpParseOptions)syntaxTree.Options; var preference = options.GetOption( CodeStyleOptions2.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyTupleElementName(argument, parseOptions)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameColon.Name.SpanStart, nameColon.ColonToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameColon.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } private void ReportDiagnosticsIfNeeded(NameEqualsSyntax nameEquals, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameEquals.Parent.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonCtor)) { return; } var preference = options.GetOption( CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyAnonymousTypeMemberName(anonCtor)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameEquals.Name.SpanStart, nameEquals.EqualsToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameEquals.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/CSharpTest/Wrapping/BinaryExpressionWrappingTests.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.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Wrapping; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping { public class BinaryExpressionWrappingTests : AbstractWrappingTests { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpWrappingCodeRefactoringProvider(); private OptionsCollection EndOfLine => Option( CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.EndOfLine); private OptionsCollection BeginningOfLine => Option( CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.BeginningOfLine); private Task TestEndOfLine(string markup, string expected) => TestInRegularAndScript1Async(markup, expected, parameters: new TestParameters( options: EndOfLine)); private Task TestBeginningOfLine(string markup, string expected) => TestInRegularAndScript1Async(markup, expected, parameters: new TestParameters( options: BeginningOfLine)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSyntaxError() { await TestMissingAsync( @"class C { void Bar() { if ([||]i && (j && ) } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSelection() { await TestMissingAsync( @"class C { void Bar() { if ([|i|] && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingBeforeExpr() { await TestMissingAsync( @"class C { void Bar() { [||]if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSingleExpr() { await TestMissingAsync( @"class C { void Bar() { if ([||]i) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithMultiLineExpression() { await TestMissingAsync( @"class C { void Bar() { if ([||]i && (j + k)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithMultiLineExpr2() { await TestMissingAsync( @"class C { void Bar() { if ([||]i && @"" "") { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf() { await TestEndOfLine( @"class C { void Bar() { if ([||]i && j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf_IncludingOp() { await TestBeginningOfLine( @"class C { void Bar() { if ([||]i && j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf2() { await TestEndOfLine( @"class C { void Bar() { if (i[||] && j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf3() { await TestEndOfLine( @"class C { void Bar() { if (i [||]&& j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf4() { await TestEndOfLine( @"class C { void Bar() { if (i &&[||] j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf5() { await TestEndOfLine( @"class C { void Bar() { if (i && [||]j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestTwoExprWrappingCases_End() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]i && j) { } } }", EndOfLine, @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestTwoExprWrappingCases_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]i && j) { } } }", BeginningOfLine, @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestThreeExprWrappingCases_End() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]i && j || k) { } } }", EndOfLine, @"class C { void Bar() { if (i && j || k) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestThreeExprWrappingCases_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]i && j || k) { } } }", BeginningOfLine, @"class C { void Bar() { if (i && j || k) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_AllOptions_NoInitialMatches_End() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ( [||]i && j || k) { } } }", EndOfLine, @"class C { void Bar() { if ( i && j || k) { } } }", @"class C { void Bar() { if ( i && j || k) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_AllOptions_NoInitialMatches_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ( [||]i && j || k) { } } }", BeginningOfLine, @"class C { void Bar() { if ( i && j || k) { } } }", @"class C { void Bar() { if ( i && j || k) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption1() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]a && b) { } } }", @"class C { void Bar() { if (a && b) { } } }", @"class C { void Bar() { if (a && b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption2_End() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]a && b) { } } }", EndOfLine, @"class C { void Bar() { if (a && b) { } } }", @"class C { void Bar() { if (a && b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption2_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]a && b) { } } }", BeginningOfLine, @"class C { void Bar() { if (a && b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInLocalInitializer_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Goo() { var v = [||]a && b && c; } }", BeginningOfLine, @"class C { void Goo() { var v = a && b && c; } }", @"class C { void Goo() { var v = a && b && c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInLocalInitializer_End() { await TestAllWrappingCasesAsync( @"class C { void Goo() { var v = [||]a && b && c; } }", EndOfLine, @"class C { void Goo() { var v = a && b && c; } }", @"class C { void Goo() { var v = a && b && c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInField_Beginning() { await TestAllWrappingCasesAsync( @"class C { bool v = [||]a && b && c; }", BeginningOfLine, @"class C { bool v = a && b && c; }", @"class C { bool v = a && b && c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInField_End() { await TestAllWrappingCasesAsync( @"class C { bool v = [||]a && b && c; }", EndOfLine, @"class C { bool v = a && b && c; }", @"class C { bool v = a && b && c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestAddition_End() { await TestAllWrappingCasesAsync( @"class C { void Bar() { var goo = [||]""now"" + ""is"" + ""the"" + ""time""; } }", EndOfLine, @"class C { void Bar() { var goo = ""now"" + ""is"" + ""the"" + ""time""; } }", @"class C { void Bar() { var goo = ""now"" + ""is"" + ""the"" + ""time""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestAddition_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Bar() { var goo = [||]""now"" + ""is"" + ""the"" + ""time""; } }", BeginningOfLine, @"class C { void Bar() { var goo = ""now"" + ""is"" + ""the"" + ""time""; } }", @"class C { void Bar() { var goo = ""now"" + ""is"" + ""the"" + ""time""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestUnderscoreName_End() { await TestEndOfLine( @"class C { void Bar() { if ([||]i is var _ && _ != null) { } } }", @"class C { void Bar() { if (i is var _ && _ != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestUnderscoreName_Beginning() { await TestBeginningOfLine( @"class C { void Bar() { if ([||]i is var _ && _ != null) { } } }", @"class C { void Bar() { if (i is var _ && _ != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInField_Already_Wrapped_Beginning() { await TestAllWrappingCasesAsync( @"class C { bool v = [||]a && b && c; }", BeginningOfLine, @"class C { bool v = a && b && c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInField_Already_Wrapped_End() { await TestAllWrappingCasesAsync( @"class C { bool v = [||]a && b && c; }", EndOfLine, @"class C { bool v = a && b && c; }"); } [WorkItem(34127, "https://github.com/dotnet/roslyn/issues/34127")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestWrapLowerPrecedenceInLargeBinary() { await TestAllWrappingCasesAsync( @"class C { bool v = [||]a + b + c + d == x * y * z; }", EndOfLine, @"class C { bool v = a + b + c + d == x * y * z; }", @"class C { bool v = a + b + c + d == x * y * z; }"); } } }
// Licensed to the .NET Foundation under one or more 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.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Wrapping; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping { public class BinaryExpressionWrappingTests : AbstractWrappingTests { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpWrappingCodeRefactoringProvider(); private OptionsCollection EndOfLine => Option( CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.EndOfLine); private OptionsCollection BeginningOfLine => Option( CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.BeginningOfLine); private Task TestEndOfLine(string markup, string expected) => TestInRegularAndScript1Async(markup, expected, parameters: new TestParameters( options: EndOfLine)); private Task TestBeginningOfLine(string markup, string expected) => TestInRegularAndScript1Async(markup, expected, parameters: new TestParameters( options: BeginningOfLine)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSyntaxError() { await TestMissingAsync( @"class C { void Bar() { if ([||]i && (j && ) } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSelection() { await TestMissingAsync( @"class C { void Bar() { if ([|i|] && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingBeforeExpr() { await TestMissingAsync( @"class C { void Bar() { [||]if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithSingleExpr() { await TestMissingAsync( @"class C { void Bar() { if ([||]i) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithMultiLineExpression() { await TestMissingAsync( @"class C { void Bar() { if ([||]i && (j + k)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestMissingWithMultiLineExpr2() { await TestMissingAsync( @"class C { void Bar() { if ([||]i && @"" "") { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf() { await TestEndOfLine( @"class C { void Bar() { if ([||]i && j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf_IncludingOp() { await TestBeginningOfLine( @"class C { void Bar() { if ([||]i && j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf2() { await TestEndOfLine( @"class C { void Bar() { if (i[||] && j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf3() { await TestEndOfLine( @"class C { void Bar() { if (i [||]&& j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf4() { await TestEndOfLine( @"class C { void Bar() { if (i &&[||] j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInIf5() { await TestEndOfLine( @"class C { void Bar() { if (i && [||]j) { } } }", @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestTwoExprWrappingCases_End() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]i && j) { } } }", EndOfLine, @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestTwoExprWrappingCases_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]i && j) { } } }", BeginningOfLine, @"class C { void Bar() { if (i && j) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestThreeExprWrappingCases_End() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]i && j || k) { } } }", EndOfLine, @"class C { void Bar() { if (i && j || k) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestThreeExprWrappingCases_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]i && j || k) { } } }", BeginningOfLine, @"class C { void Bar() { if (i && j || k) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_AllOptions_NoInitialMatches_End() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ( [||]i && j || k) { } } }", EndOfLine, @"class C { void Bar() { if ( i && j || k) { } } }", @"class C { void Bar() { if ( i && j || k) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_AllOptions_NoInitialMatches_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ( [||]i && j || k) { } } }", BeginningOfLine, @"class C { void Bar() { if ( i && j || k) { } } }", @"class C { void Bar() { if ( i && j || k) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption1() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]a && b) { } } }", @"class C { void Bar() { if (a && b) { } } }", @"class C { void Bar() { if (a && b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption2_End() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]a && b) { } } }", EndOfLine, @"class C { void Bar() { if (a && b) { } } }", @"class C { void Bar() { if (a && b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task Test_DoNotOfferExistingOption2_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Bar() { if ([||]a && b) { } } }", BeginningOfLine, @"class C { void Bar() { if (a && b) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInLocalInitializer_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Goo() { var v = [||]a && b && c; } }", BeginningOfLine, @"class C { void Goo() { var v = a && b && c; } }", @"class C { void Goo() { var v = a && b && c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInLocalInitializer_End() { await TestAllWrappingCasesAsync( @"class C { void Goo() { var v = [||]a && b && c; } }", EndOfLine, @"class C { void Goo() { var v = a && b && c; } }", @"class C { void Goo() { var v = a && b && c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInField_Beginning() { await TestAllWrappingCasesAsync( @"class C { bool v = [||]a && b && c; }", BeginningOfLine, @"class C { bool v = a && b && c; }", @"class C { bool v = a && b && c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInField_End() { await TestAllWrappingCasesAsync( @"class C { bool v = [||]a && b && c; }", EndOfLine, @"class C { bool v = a && b && c; }", @"class C { bool v = a && b && c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestAddition_End() { await TestAllWrappingCasesAsync( @"class C { void Bar() { var goo = [||]""now"" + ""is"" + ""the"" + ""time""; } }", EndOfLine, @"class C { void Bar() { var goo = ""now"" + ""is"" + ""the"" + ""time""; } }", @"class C { void Bar() { var goo = ""now"" + ""is"" + ""the"" + ""time""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestAddition_Beginning() { await TestAllWrappingCasesAsync( @"class C { void Bar() { var goo = [||]""now"" + ""is"" + ""the"" + ""time""; } }", BeginningOfLine, @"class C { void Bar() { var goo = ""now"" + ""is"" + ""the"" + ""time""; } }", @"class C { void Bar() { var goo = ""now"" + ""is"" + ""the"" + ""time""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestUnderscoreName_End() { await TestEndOfLine( @"class C { void Bar() { if ([||]i is var _ && _ != null) { } } }", @"class C { void Bar() { if (i is var _ && _ != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestUnderscoreName_Beginning() { await TestBeginningOfLine( @"class C { void Bar() { if ([||]i is var _ && _ != null) { } } }", @"class C { void Bar() { if (i is var _ && _ != null) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInField_Already_Wrapped_Beginning() { await TestAllWrappingCasesAsync( @"class C { bool v = [||]a && b && c; }", BeginningOfLine, @"class C { bool v = a && b && c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestInField_Already_Wrapped_End() { await TestAllWrappingCasesAsync( @"class C { bool v = [||]a && b && c; }", EndOfLine, @"class C { bool v = a && b && c; }"); } [WorkItem(34127, "https://github.com/dotnet/roslyn/issues/34127")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)] public async Task TestWrapLowerPrecedenceInLargeBinary() { await TestAllWrappingCasesAsync( @"class C { bool v = [||]a + b + c + d == x * y * z; }", EndOfLine, @"class C { bool v = a + b + c + d == x * y * z; }", @"class C { bool v = a + b + c + d == x * y * z; }"); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/LiveShare/Impl/LiveShareInitializeHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol; using Microsoft.VisualStudio.LiveShare.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Shims { internal class LiveShareInitializeHandler : ILspRequestHandler<InitializeParams, InitializeResult, Solution> { private static readonly InitializeResult s_initializeResult = new InitializeResult { Capabilities = new ServerCapabilities { CodeActionProvider = false, ReferencesProvider = true, RenameProvider = false, } }; public Task<InitializeResult> HandleAsync(InitializeParams param, RequestContext<Solution> requestContext, CancellationToken cancellationToken) => Task.FromResult(s_initializeResult); } [ExportLspRequestHandler(LiveShareConstants.RoslynContractName, Methods.InitializeName)] [Obsolete("Used for backwards compatibility with old liveshare clients.")] internal class RoslynInitializeHandlerShim : LiveShareInitializeHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RoslynInitializeHandlerShim() { } } [ExportLspRequestHandler(LiveShareConstants.CSharpContractName, Methods.InitializeName)] internal class CSharpInitializeHandlerShim : LiveShareInitializeHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpInitializeHandlerShim() { } } [ExportLspRequestHandler(LiveShareConstants.VisualBasicContractName, Methods.InitializeName)] internal class VisualBasicInitializeHandlerShim : LiveShareInitializeHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualBasicInitializeHandlerShim() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol; using Microsoft.VisualStudio.LiveShare.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Shims { internal class LiveShareInitializeHandler : ILspRequestHandler<InitializeParams, InitializeResult, Solution> { private static readonly InitializeResult s_initializeResult = new InitializeResult { Capabilities = new ServerCapabilities { CodeActionProvider = false, ReferencesProvider = true, RenameProvider = false, } }; public Task<InitializeResult> HandleAsync(InitializeParams param, RequestContext<Solution> requestContext, CancellationToken cancellationToken) => Task.FromResult(s_initializeResult); } [ExportLspRequestHandler(LiveShareConstants.RoslynContractName, Methods.InitializeName)] [Obsolete("Used for backwards compatibility with old liveshare clients.")] internal class RoslynInitializeHandlerShim : LiveShareInitializeHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RoslynInitializeHandlerShim() { } } [ExportLspRequestHandler(LiveShareConstants.CSharpContractName, Methods.InitializeName)] internal class CSharpInitializeHandlerShim : LiveShareInitializeHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpInitializeHandlerShim() { } } [ExportLspRequestHandler(LiveShareConstants.VisualBasicContractName, Methods.InitializeName)] internal class VisualBasicInitializeHandlerShim : LiveShareInitializeHandler { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualBasicInitializeHandlerShim() { } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Test/Symbol/Symbols/Retargeting/RetargetCustomAttributes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System.Collections.Generic; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Retargeting { public class RetargetCustomAttributes : CSharpTestBase { internal class Test01 { public CSharpCompilationReference c1, c2; public AssemblySymbol c1MscorLibAssemblyRef, c2MscorlibAssemblyRef; public NamedTypeSymbol oldMsCorLib_debuggerTypeProxyAttributeType, newMsCorLib_debuggerTypeProxyAttributeType; public MethodSymbol oldMsCorLib_debuggerTypeProxyAttributeCtor, newMsCorLib_debuggerTypeProxyAttributeCtor; public NamedTypeSymbol oldMsCorLib_systemType, newMsCorLib_systemType; private static readonly AttributeDescription s_attribute = new AttributeDescription( "System.Diagnostics", "DebuggerTypeProxyAttribute", new byte[][] { new byte[] { (byte)SignatureAttributes.Instance, 1, (byte)SignatureTypeCode.Void, (byte)SignatureTypeCode.TypeHandle, (byte)AttributeDescription.TypeHandleTarget.SystemType } }); public Test01() { string source = @" using System.Diagnostics; [assembly: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] [module: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] class TestClass { [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] public int testField; [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] public int TestProperty { [return: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] get { return testField; } } [return: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] public T TestMethod<[DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] T> ([DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] T testParameter) { return testParameter; } }"; var compilation1 = CSharpCompilation.Create("C1", new[] { Parse(source) }, new[] { OldMsCorLib }, TestOptions.ReleaseDll); c1 = new CSharpCompilationReference(compilation1); var c1Assembly = compilation1.Assembly; var compilation2 = CSharpCompilation.Create("C2", references: new MetadataReference[] { NewMsCorLib, c1 }); c2 = new CSharpCompilationReference(compilation2); var c1AsmRef = compilation2.GetReferencedAssemblySymbol(c1); Assert.NotSame(c1Assembly, c1AsmRef); c1MscorLibAssemblyRef = compilation1.GetReferencedAssemblySymbol(OldMsCorLib); c2MscorlibAssemblyRef = compilation2.GetReferencedAssemblySymbol(NewMsCorLib); Assert.NotSame(c1MscorLibAssemblyRef, c2MscorlibAssemblyRef); oldMsCorLib_systemType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Type"); newMsCorLib_systemType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Type"); Assert.NotSame(oldMsCorLib_systemType, newMsCorLib_systemType); oldMsCorLib_debuggerTypeProxyAttributeType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Diagnostics.DebuggerTypeProxyAttribute"); newMsCorLib_debuggerTypeProxyAttributeType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Diagnostics.DebuggerTypeProxyAttribute"); Assert.NotSame(oldMsCorLib_debuggerTypeProxyAttributeType, newMsCorLib_debuggerTypeProxyAttributeType); oldMsCorLib_debuggerTypeProxyAttributeCtor = (MethodSymbol)oldMsCorLib_debuggerTypeProxyAttributeType.GetMembers(".ctor").Single( m => ((MethodSymbol)m).ParameterCount == 1 && TypeSymbol.Equals(((MethodSymbol)m).GetParameterType(0), oldMsCorLib_systemType, TypeCompareKind.ConsiderEverything2)); newMsCorLib_debuggerTypeProxyAttributeCtor = (MethodSymbol)newMsCorLib_debuggerTypeProxyAttributeType.GetMembers(".ctor").Single( m => ((MethodSymbol)m).ParameterCount == 1 && TypeSymbol.Equals(((MethodSymbol)m).GetParameterType(0), newMsCorLib_systemType, TypeCompareKind.ConsiderEverything2)); Assert.NotSame(oldMsCorLib_debuggerTypeProxyAttributeCtor, newMsCorLib_debuggerTypeProxyAttributeCtor); } public void TestAttributeRetargeting(Symbol symbol) { // Verify GetAttributes() TestAttributeRetargeting(symbol.GetAttributes()); // Verify GetAttributes(AttributeType from Retargeted assembly) TestAttributeRetargeting(symbol.GetAttributes(newMsCorLib_debuggerTypeProxyAttributeType)); // Verify GetAttributes(AttributeType from Underlying assembly) Assert.Empty(symbol.GetAttributes(oldMsCorLib_debuggerTypeProxyAttributeType)); // Verify GetAttributes(AttributeCtor from Retargeted assembly) TestAttributeRetargeting(symbol.GetAttributes(newMsCorLib_debuggerTypeProxyAttributeType)); // Verify GetAttributes(AttributeCtor from Underlying assembly) Assert.Empty(symbol.GetAttributes(oldMsCorLib_debuggerTypeProxyAttributeType)); // Verify GetAttributes(namespaceName, typeName, ctorSignature) TestAttributeRetargeting(symbol.GetAttributes(s_attribute)); } public void TestAttributeRetargeting_ReturnTypeAttributes(MethodSymbol symbol) { // Verify GetReturnTypeAttributes() TestAttributeRetargeting(symbol.GetReturnTypeAttributes()); // Verify GetReturnTypeAttributes(AttributeType from Retargeted assembly) TestAttributeRetargeting(symbol.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, newMsCorLib_debuggerTypeProxyAttributeType, TypeCompareKind.ConsiderEverything2))); // Verify GetReturnTypeAttributes(AttributeType from Underlying assembly) returns nothing. Shouldn't match to old attr type Assert.Empty(symbol.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, oldMsCorLib_debuggerTypeProxyAttributeType, TypeCompareKind.ConsiderEverything2))); // Verify GetReturnTypeAttributes(AttributeCtor from Retargeted assembly) TestAttributeRetargeting(symbol.GetReturnTypeAttributes().Where(a => a.AttributeConstructor == newMsCorLib_debuggerTypeProxyAttributeCtor)); // Verify GetReturnTypeAttributes(AttributeCtor from Underlying assembly) returns nothing. Shouldn't match to old attr type. Assert.Empty(symbol.GetReturnTypeAttributes().Where(a => a.AttributeConstructor == oldMsCorLib_debuggerTypeProxyAttributeCtor)); } private void TestAttributeRetargeting(IEnumerable<CSharpAttributeData> attributes) { Assert.Equal(1, attributes.Count()); var attribute = attributes.First(); Assert.IsType<RetargetingAttributeData>(attribute); Assert.Same(newMsCorLib_debuggerTypeProxyAttributeType, attribute.AttributeClass); Assert.Same(newMsCorLib_debuggerTypeProxyAttributeCtor, attribute.AttributeConstructor); Assert.Same(newMsCorLib_systemType, attribute.AttributeConstructor.GetParameterType(0)); Assert.Equal(1, attribute.CommonConstructorArguments.Length); attribute.VerifyValue(0, TypedConstantKind.Type, newMsCorLib_systemType); Assert.Equal(2, attribute.CommonNamedArguments.Length); attribute.VerifyNamedArgumentValue<object>(0, "Target", TypedConstantKind.Type, typeof(int[])); attribute.VerifyNamedArgumentValue(1, "TargetTypeName", TypedConstantKind.Primitive, "IntArrayType"); } } private static MetadataReference OldMsCorLib { get { return TestMetadata.Net40.mscorlib; } } private static MetadataReference NewMsCorLib { get { return TestMetadata.Net451.mscorlib; } } [Fact] public void Test01_AssemblyAttribute() { Test01 test = new Test01(); var c1AsmRef = test.c2.Compilation.GetReferencedAssemblySymbol(test.c1); Assert.IsType<RetargetingAssemblySymbol>(c1AsmRef); test.TestAttributeRetargeting(c1AsmRef); } [Fact] public void Test01_ModuleAttribute() { Test01 test = new Test01(); var c1AsmRef = test.c2.Compilation.GetReferencedAssemblySymbol(test.c1); var c1ModuleSym = c1AsmRef.Modules[0]; Assert.IsType<RetargetingModuleSymbol>(c1ModuleSym); test.TestAttributeRetargeting(c1ModuleSym); } [Fact] public void Test01_NamedTypeAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); Assert.IsType<RetargetingNamedTypeSymbol>(testClass); test.TestAttributeRetargeting(testClass); } [Fact] public void Test01_FieldAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); FieldSymbol testField = testClass.GetMembers("testField").OfType<FieldSymbol>().Single(); Assert.IsType<RetargetingFieldSymbol>(testField); test.TestAttributeRetargeting(testField); } [Fact] public void Test01_PropertyAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); PropertySymbol testProperty = testClass.GetMembers("TestProperty").OfType<PropertySymbol>().Single(); Assert.IsType<RetargetingPropertySymbol>(testProperty); test.TestAttributeRetargeting(testProperty); MethodSymbol testMethod = testProperty.GetMethod; Assert.IsType<RetargetingMethodSymbol>(testMethod); test.TestAttributeRetargeting_ReturnTypeAttributes(testMethod); } [Fact] public void Test01_MethodAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); MethodSymbol testMethod = testClass.GetMembers("TestMethod").OfType<MethodSymbol>().Single(); Assert.IsType<RetargetingMethodSymbol>(testMethod); test.TestAttributeRetargeting(testMethod); } [Fact] public void Test01_TypeParameterAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); MethodSymbol testMethod = testClass.GetMembers("TestMethod").OfType<MethodSymbol>().Single(); Assert.IsType<RetargetingMethodSymbol>(testMethod); TypeParameterSymbol testTypeParameter = testMethod.TypeParameters[0]; Assert.IsType<RetargetingTypeParameterSymbol>(testTypeParameter); test.TestAttributeRetargeting(testTypeParameter); } [Fact] public void Test01_ParameterAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); MethodSymbol testMethod = testClass.GetMembers("TestMethod").OfType<MethodSymbol>().Single(); Assert.IsType<RetargetingMethodSymbol>(testMethod); ParameterSymbol testParameter = testMethod.Parameters[0]; Assert.IsType<RetargetingMethodParameterSymbol>(testParameter); test.TestAttributeRetargeting(testParameter); } [Fact] public void Test01_ReturnTypeAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); MethodSymbol testMethod = testClass.GetMembers("TestMethod").OfType<MethodSymbol>().Single(); Assert.IsType<RetargetingMethodSymbol>(testMethod); test.TestAttributeRetargeting_ReturnTypeAttributes(testMethod); } [Fact] [WorkItem(569089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569089"), WorkItem(575948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575948")] public void NullArrays() { var source1 = @" using System; public class A : Attribute { public A(object[] a, int[] b) { } public object[] P { get; set; } public int[] F; } [A(null, null, P = null, F = null)] public class C { } "; var source2 = @" "; var c1 = CreateEmptyCompilation(source1, new[] { OldMsCorLib }); var c2 = CreateEmptyCompilation(source2, new MetadataReference[] { NewMsCorLib, new CSharpCompilationReference(c1) }); var c = c2.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.IsType<RetargetingNamedTypeSymbol>(c); var attr = c.GetAttributes().Single(); var args = attr.ConstructorArguments.ToArray(); Assert.True(args[0].IsNull); Assert.Equal("object[]", args[0].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[0].Value); Assert.True(args[1].IsNull); Assert.Equal("int[]", args[1].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[1].Value); var named = attr.NamedArguments.ToDictionary(e => e.Key, e => e.Value); Assert.True(named["P"].IsNull); Assert.Equal("object[]", named["P"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["P"].Value); Assert.True(named["F"].IsNull); Assert.Equal("int[]", named["F"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["F"].Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System.Collections.Generic; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Retargeting { public class RetargetCustomAttributes : CSharpTestBase { internal class Test01 { public CSharpCompilationReference c1, c2; public AssemblySymbol c1MscorLibAssemblyRef, c2MscorlibAssemblyRef; public NamedTypeSymbol oldMsCorLib_debuggerTypeProxyAttributeType, newMsCorLib_debuggerTypeProxyAttributeType; public MethodSymbol oldMsCorLib_debuggerTypeProxyAttributeCtor, newMsCorLib_debuggerTypeProxyAttributeCtor; public NamedTypeSymbol oldMsCorLib_systemType, newMsCorLib_systemType; private static readonly AttributeDescription s_attribute = new AttributeDescription( "System.Diagnostics", "DebuggerTypeProxyAttribute", new byte[][] { new byte[] { (byte)SignatureAttributes.Instance, 1, (byte)SignatureTypeCode.Void, (byte)SignatureTypeCode.TypeHandle, (byte)AttributeDescription.TypeHandleTarget.SystemType } }); public Test01() { string source = @" using System.Diagnostics; [assembly: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] [module: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] class TestClass { [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] public int testField; [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] public int TestProperty { [return: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] get { return testField; } } [return: DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] [DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] public T TestMethod<[DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] T> ([DebuggerTypeProxyAttribute(typeof(System.Type), Target = typeof(int[]), TargetTypeName = ""IntArrayType"" )] T testParameter) { return testParameter; } }"; var compilation1 = CSharpCompilation.Create("C1", new[] { Parse(source) }, new[] { OldMsCorLib }, TestOptions.ReleaseDll); c1 = new CSharpCompilationReference(compilation1); var c1Assembly = compilation1.Assembly; var compilation2 = CSharpCompilation.Create("C2", references: new MetadataReference[] { NewMsCorLib, c1 }); c2 = new CSharpCompilationReference(compilation2); var c1AsmRef = compilation2.GetReferencedAssemblySymbol(c1); Assert.NotSame(c1Assembly, c1AsmRef); c1MscorLibAssemblyRef = compilation1.GetReferencedAssemblySymbol(OldMsCorLib); c2MscorlibAssemblyRef = compilation2.GetReferencedAssemblySymbol(NewMsCorLib); Assert.NotSame(c1MscorLibAssemblyRef, c2MscorlibAssemblyRef); oldMsCorLib_systemType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Type"); newMsCorLib_systemType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Type"); Assert.NotSame(oldMsCorLib_systemType, newMsCorLib_systemType); oldMsCorLib_debuggerTypeProxyAttributeType = c1MscorLibAssemblyRef.GetTypeByMetadataName("System.Diagnostics.DebuggerTypeProxyAttribute"); newMsCorLib_debuggerTypeProxyAttributeType = c2MscorlibAssemblyRef.GetTypeByMetadataName("System.Diagnostics.DebuggerTypeProxyAttribute"); Assert.NotSame(oldMsCorLib_debuggerTypeProxyAttributeType, newMsCorLib_debuggerTypeProxyAttributeType); oldMsCorLib_debuggerTypeProxyAttributeCtor = (MethodSymbol)oldMsCorLib_debuggerTypeProxyAttributeType.GetMembers(".ctor").Single( m => ((MethodSymbol)m).ParameterCount == 1 && TypeSymbol.Equals(((MethodSymbol)m).GetParameterType(0), oldMsCorLib_systemType, TypeCompareKind.ConsiderEverything2)); newMsCorLib_debuggerTypeProxyAttributeCtor = (MethodSymbol)newMsCorLib_debuggerTypeProxyAttributeType.GetMembers(".ctor").Single( m => ((MethodSymbol)m).ParameterCount == 1 && TypeSymbol.Equals(((MethodSymbol)m).GetParameterType(0), newMsCorLib_systemType, TypeCompareKind.ConsiderEverything2)); Assert.NotSame(oldMsCorLib_debuggerTypeProxyAttributeCtor, newMsCorLib_debuggerTypeProxyAttributeCtor); } public void TestAttributeRetargeting(Symbol symbol) { // Verify GetAttributes() TestAttributeRetargeting(symbol.GetAttributes()); // Verify GetAttributes(AttributeType from Retargeted assembly) TestAttributeRetargeting(symbol.GetAttributes(newMsCorLib_debuggerTypeProxyAttributeType)); // Verify GetAttributes(AttributeType from Underlying assembly) Assert.Empty(symbol.GetAttributes(oldMsCorLib_debuggerTypeProxyAttributeType)); // Verify GetAttributes(AttributeCtor from Retargeted assembly) TestAttributeRetargeting(symbol.GetAttributes(newMsCorLib_debuggerTypeProxyAttributeType)); // Verify GetAttributes(AttributeCtor from Underlying assembly) Assert.Empty(symbol.GetAttributes(oldMsCorLib_debuggerTypeProxyAttributeType)); // Verify GetAttributes(namespaceName, typeName, ctorSignature) TestAttributeRetargeting(symbol.GetAttributes(s_attribute)); } public void TestAttributeRetargeting_ReturnTypeAttributes(MethodSymbol symbol) { // Verify GetReturnTypeAttributes() TestAttributeRetargeting(symbol.GetReturnTypeAttributes()); // Verify GetReturnTypeAttributes(AttributeType from Retargeted assembly) TestAttributeRetargeting(symbol.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, newMsCorLib_debuggerTypeProxyAttributeType, TypeCompareKind.ConsiderEverything2))); // Verify GetReturnTypeAttributes(AttributeType from Underlying assembly) returns nothing. Shouldn't match to old attr type Assert.Empty(symbol.GetReturnTypeAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, oldMsCorLib_debuggerTypeProxyAttributeType, TypeCompareKind.ConsiderEverything2))); // Verify GetReturnTypeAttributes(AttributeCtor from Retargeted assembly) TestAttributeRetargeting(symbol.GetReturnTypeAttributes().Where(a => a.AttributeConstructor == newMsCorLib_debuggerTypeProxyAttributeCtor)); // Verify GetReturnTypeAttributes(AttributeCtor from Underlying assembly) returns nothing. Shouldn't match to old attr type. Assert.Empty(symbol.GetReturnTypeAttributes().Where(a => a.AttributeConstructor == oldMsCorLib_debuggerTypeProxyAttributeCtor)); } private void TestAttributeRetargeting(IEnumerable<CSharpAttributeData> attributes) { Assert.Equal(1, attributes.Count()); var attribute = attributes.First(); Assert.IsType<RetargetingAttributeData>(attribute); Assert.Same(newMsCorLib_debuggerTypeProxyAttributeType, attribute.AttributeClass); Assert.Same(newMsCorLib_debuggerTypeProxyAttributeCtor, attribute.AttributeConstructor); Assert.Same(newMsCorLib_systemType, attribute.AttributeConstructor.GetParameterType(0)); Assert.Equal(1, attribute.CommonConstructorArguments.Length); attribute.VerifyValue(0, TypedConstantKind.Type, newMsCorLib_systemType); Assert.Equal(2, attribute.CommonNamedArguments.Length); attribute.VerifyNamedArgumentValue<object>(0, "Target", TypedConstantKind.Type, typeof(int[])); attribute.VerifyNamedArgumentValue(1, "TargetTypeName", TypedConstantKind.Primitive, "IntArrayType"); } } private static MetadataReference OldMsCorLib { get { return TestMetadata.Net40.mscorlib; } } private static MetadataReference NewMsCorLib { get { return TestMetadata.Net451.mscorlib; } } [Fact] public void Test01_AssemblyAttribute() { Test01 test = new Test01(); var c1AsmRef = test.c2.Compilation.GetReferencedAssemblySymbol(test.c1); Assert.IsType<RetargetingAssemblySymbol>(c1AsmRef); test.TestAttributeRetargeting(c1AsmRef); } [Fact] public void Test01_ModuleAttribute() { Test01 test = new Test01(); var c1AsmRef = test.c2.Compilation.GetReferencedAssemblySymbol(test.c1); var c1ModuleSym = c1AsmRef.Modules[0]; Assert.IsType<RetargetingModuleSymbol>(c1ModuleSym); test.TestAttributeRetargeting(c1ModuleSym); } [Fact] public void Test01_NamedTypeAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); Assert.IsType<RetargetingNamedTypeSymbol>(testClass); test.TestAttributeRetargeting(testClass); } [Fact] public void Test01_FieldAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); FieldSymbol testField = testClass.GetMembers("testField").OfType<FieldSymbol>().Single(); Assert.IsType<RetargetingFieldSymbol>(testField); test.TestAttributeRetargeting(testField); } [Fact] public void Test01_PropertyAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); PropertySymbol testProperty = testClass.GetMembers("TestProperty").OfType<PropertySymbol>().Single(); Assert.IsType<RetargetingPropertySymbol>(testProperty); test.TestAttributeRetargeting(testProperty); MethodSymbol testMethod = testProperty.GetMethod; Assert.IsType<RetargetingMethodSymbol>(testMethod); test.TestAttributeRetargeting_ReturnTypeAttributes(testMethod); } [Fact] public void Test01_MethodAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); MethodSymbol testMethod = testClass.GetMembers("TestMethod").OfType<MethodSymbol>().Single(); Assert.IsType<RetargetingMethodSymbol>(testMethod); test.TestAttributeRetargeting(testMethod); } [Fact] public void Test01_TypeParameterAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); MethodSymbol testMethod = testClass.GetMembers("TestMethod").OfType<MethodSymbol>().Single(); Assert.IsType<RetargetingMethodSymbol>(testMethod); TypeParameterSymbol testTypeParameter = testMethod.TypeParameters[0]; Assert.IsType<RetargetingTypeParameterSymbol>(testTypeParameter); test.TestAttributeRetargeting(testTypeParameter); } [Fact] public void Test01_ParameterAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); MethodSymbol testMethod = testClass.GetMembers("TestMethod").OfType<MethodSymbol>().Single(); Assert.IsType<RetargetingMethodSymbol>(testMethod); ParameterSymbol testParameter = testMethod.Parameters[0]; Assert.IsType<RetargetingMethodParameterSymbol>(testParameter); test.TestAttributeRetargeting(testParameter); } [Fact] public void Test01_ReturnTypeAttribute() { Test01 test = new Test01(); var testClass = test.c2.Compilation.GlobalNamespace.GetTypeMembers("TestClass").Single(); MethodSymbol testMethod = testClass.GetMembers("TestMethod").OfType<MethodSymbol>().Single(); Assert.IsType<RetargetingMethodSymbol>(testMethod); test.TestAttributeRetargeting_ReturnTypeAttributes(testMethod); } [Fact] [WorkItem(569089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569089"), WorkItem(575948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575948")] public void NullArrays() { var source1 = @" using System; public class A : Attribute { public A(object[] a, int[] b) { } public object[] P { get; set; } public int[] F; } [A(null, null, P = null, F = null)] public class C { } "; var source2 = @" "; var c1 = CreateEmptyCompilation(source1, new[] { OldMsCorLib }); var c2 = CreateEmptyCompilation(source2, new MetadataReference[] { NewMsCorLib, new CSharpCompilationReference(c1) }); var c = c2.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.IsType<RetargetingNamedTypeSymbol>(c); var attr = c.GetAttributes().Single(); var args = attr.ConstructorArguments.ToArray(); Assert.True(args[0].IsNull); Assert.Equal("object[]", args[0].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[0].Value); Assert.True(args[1].IsNull); Assert.Equal("int[]", args[1].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => args[1].Value); var named = attr.NamedArguments.ToDictionary(e => e.Key, e => e.Value); Assert.True(named["P"].IsNull); Assert.Equal("object[]", named["P"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["P"].Value); Assert.True(named["F"].IsNull); Assert.Equal("int[]", named["F"].Type.ToDisplayString()); Assert.Throws<InvalidOperationException>(() => named["F"].Value); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/Core.Wpf/Peek/PeekableItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { internal abstract class PeekableItem : IPeekableItem { protected readonly IPeekResultFactory PeekResultFactory; protected PeekableItem(IPeekResultFactory peekResultFactory) => this.PeekResultFactory = peekResultFactory; public string DisplayName => // This is unused, and was supposed to have been removed from IPeekableItem. null; public abstract IEnumerable<IPeekRelationship> Relationships { get; } public abstract IPeekResultSource GetOrCreateResultSource(string relationshipName); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { internal abstract class PeekableItem : IPeekableItem { protected readonly IPeekResultFactory PeekResultFactory; protected PeekableItem(IPeekResultFactory peekResultFactory) => this.PeekResultFactory = peekResultFactory; public string DisplayName => // This is unused, and was supposed to have been removed from IPeekableItem. null; public abstract IEnumerable<IPeekRelationship> Relationships { get; } public abstract IPeekResultSource GetOrCreateResultSource(string relationshipName); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Impl/CodeModel/Collections/NodeSnapshot.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { internal class NodeSnapshot : Snapshot { private readonly CodeModelState _state; private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNode _parentNode; private readonly AbstractCodeElement _parentElement; private readonly ImmutableArray<SyntaxNode> _nodes; public NodeSnapshot( CodeModelState state, ComHandle<EnvDTE.FileCodeModel, FileCodeModel> fileCodeModel, SyntaxNode parentNode, AbstractCodeElement parentElement, ImmutableArray<SyntaxNode> nodes) { _state = state; _fileCodeModel = fileCodeModel; _parentNode = parentNode; _parentElement = parentElement; _nodes = nodes; } private ICodeModelService CodeModelService { get { return _state.CodeModelService; } } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node) { this.CodeModelService.GetOptionNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return CodeOptionsStatement.Create(_state, this.FileCodeModel, name, ordinal); } private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node) { var name = this.CodeModelService.GetImportNamespaceOrType(node); return CodeImport.Create(_state, this.FileCodeModel, _parentElement, name); } private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node) { this.CodeModelService.GetAttributeNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return (EnvDTE.CodeElement)CodeAttribute.Create(_state, this.FileCodeModel, _parentElement, name, ordinal); } private EnvDTE.CodeElement CreateCodeParameter(SyntaxNode node) { Debug.Assert(_parentElement is AbstractCodeMember, "Parameters should always have an associated member!"); var name = this.CodeModelService.GetParameterName(node); return (EnvDTE.CodeElement)CodeParameter.Create(_state, (AbstractCodeMember)_parentElement, name); } public override int Count { get { return _nodes.Length; } } public override EnvDTE.CodeElement this[int index] { get { if (index < 0 || index >= _nodes.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } var node = _nodes[index]; if (this.CodeModelService.IsOptionNode(node)) { return CreateCodeOptionsStatement(node); } else if (this.CodeModelService.IsImportNode(node)) { return CreateCodeImport(node); } else if (this.CodeModelService.IsAttributeNode(node)) { return CreateCodeAttribute(node); } else if (this.CodeModelService.IsParameterNode(node)) { return CreateCodeParameter(node); } // The node must be something that the FileCodeModel can create. return this.FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { internal class NodeSnapshot : Snapshot { private readonly CodeModelState _state; private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNode _parentNode; private readonly AbstractCodeElement _parentElement; private readonly ImmutableArray<SyntaxNode> _nodes; public NodeSnapshot( CodeModelState state, ComHandle<EnvDTE.FileCodeModel, FileCodeModel> fileCodeModel, SyntaxNode parentNode, AbstractCodeElement parentElement, ImmutableArray<SyntaxNode> nodes) { _state = state; _fileCodeModel = fileCodeModel; _parentNode = parentNode; _parentElement = parentElement; _nodes = nodes; } private ICodeModelService CodeModelService { get { return _state.CodeModelService; } } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node) { this.CodeModelService.GetOptionNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return CodeOptionsStatement.Create(_state, this.FileCodeModel, name, ordinal); } private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node) { var name = this.CodeModelService.GetImportNamespaceOrType(node); return CodeImport.Create(_state, this.FileCodeModel, _parentElement, name); } private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node) { this.CodeModelService.GetAttributeNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return (EnvDTE.CodeElement)CodeAttribute.Create(_state, this.FileCodeModel, _parentElement, name, ordinal); } private EnvDTE.CodeElement CreateCodeParameter(SyntaxNode node) { Debug.Assert(_parentElement is AbstractCodeMember, "Parameters should always have an associated member!"); var name = this.CodeModelService.GetParameterName(node); return (EnvDTE.CodeElement)CodeParameter.Create(_state, (AbstractCodeMember)_parentElement, name); } public override int Count { get { return _nodes.Length; } } public override EnvDTE.CodeElement this[int index] { get { if (index < 0 || index >= _nodes.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } var node = _nodes[index]; if (this.CodeModelService.IsOptionNode(node)) { return CreateCodeOptionsStatement(node); } else if (this.CodeModelService.IsImportNode(node)) { return CreateCodeImport(node); } else if (this.CodeModelService.IsAttributeNode(node)) { return CreateCodeAttribute(node); } else if (this.CodeModelService.IsParameterNode(node)) { return CreateCodeParameter(node); } // The node must be something that the FileCodeModel can create. return this.FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/CSharpTest2/Recommendations/AsyncKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class AsyncKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMethodDeclaration1() { await VerifyKeywordAsync(@"class C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMethodDeclaration2() { await VerifyKeywordAsync(@"class C { public $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMethodDeclaration3() { await VerifyKeywordAsync(@"class C { $$ public void goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMethodDeclarationInGlobalStatement1() { const string text = @"$$"; await VerifyKeywordAsync(SourceCodeKind.Script, text); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMethodDeclarationInGlobalStatement2() { const string text = @"public $$"; await VerifyKeywordAsync(SourceCodeKind.Script, text); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExpressionContext() { await VerifyKeywordAsync(@"class C { void goo() { goo($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameter() { await VerifyAbsenceAsync(@"class C { void goo($$) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeLambda() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = $$ () => 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStaticLambda() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = $$ static () => 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticInLambda() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = static $$ () => 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticInExpression() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = static $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDuplicateStaticInExpression() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = static static $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticAsyncInExpression() { await VerifyAbsenceAsync(@" class Program { static void Main(string[] args) { var z = static async $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncStaticInExpression() { await VerifyAbsenceAsync(@" class Program { static void Main(string[] args) { var z = async static $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttribute() { await VerifyAbsenceAsync(@" class C { [$$ void M() { } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeArgument() { await VerifyAbsenceAsync(@" class C { [Attr($$ void M() { } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStaticInExpression() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = $$ static } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotIfAlreadyAsync2() { await VerifyAbsenceAsync(@" class Program { static void Main(string[] args) { var z = async $$ () => 2; } }"); } [WorkItem(578061, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578061")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInNamespace() { await VerifyAbsenceAsync(@" namespace Goo { $$ }"); } [WorkItem(578069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578069")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartialInNamespace() { await VerifyAbsenceAsync(@" namespace Goo { partial $$ }"); } [WorkItem(578750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578750")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartialInClass() { await VerifyAbsenceAsync(@" class Goo { partial $$ }"); } [WorkItem(578750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578750")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttribute() { await VerifyKeywordAsync(@" class Goo { [Attr] $$ }"); } [Theory] [CombinatorialData] [WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task TestLocalFunction(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory] [CombinatorialData] [WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction2(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"unsafe $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory] [CombinatorialData] [WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction3(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"unsafe $$ void L() { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory] [CombinatorialData] [WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction4(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$ void L() { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact] [WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction5() { await VerifyKeywordAsync(@" class Goo { public void M(Action<int> a) { M(async () => { $$ }); } }"); } [Theory] [CombinatorialData] [WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction6(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"int $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory] [CombinatorialData] [WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction7(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class AsyncKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMethodDeclaration1() { await VerifyKeywordAsync(@"class C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMethodDeclaration2() { await VerifyKeywordAsync(@"class C { public $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMethodDeclaration3() { await VerifyKeywordAsync(@"class C { $$ public void goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMethodDeclarationInGlobalStatement1() { const string text = @"$$"; await VerifyKeywordAsync(SourceCodeKind.Script, text); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestMethodDeclarationInGlobalStatement2() { const string text = @"public $$"; await VerifyKeywordAsync(SourceCodeKind.Script, text); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExpressionContext() { await VerifyKeywordAsync(@"class C { void goo() { goo($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameter() { await VerifyAbsenceAsync(@"class C { void goo($$) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeLambda() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = $$ () => 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStaticLambda() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = $$ static () => 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticInLambda() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = static $$ () => 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticInExpression() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = static $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDuplicateStaticInExpression() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = static static $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticAsyncInExpression() { await VerifyAbsenceAsync(@" class Program { static void Main(string[] args) { var z = static async $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncStaticInExpression() { await VerifyAbsenceAsync(@" class Program { static void Main(string[] args) { var z = async static $$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttribute() { await VerifyAbsenceAsync(@" class C { [$$ void M() { } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeArgument() { await VerifyAbsenceAsync(@" class C { [Attr($$ void M() { } } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStaticInExpression() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { var z = $$ static } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotIfAlreadyAsync2() { await VerifyAbsenceAsync(@" class Program { static void Main(string[] args) { var z = async $$ () => 2; } }"); } [WorkItem(578061, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578061")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInNamespace() { await VerifyAbsenceAsync(@" namespace Goo { $$ }"); } [WorkItem(578069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578069")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartialInNamespace() { await VerifyAbsenceAsync(@" namespace Goo { partial $$ }"); } [WorkItem(578750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578750")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartialInClass() { await VerifyAbsenceAsync(@" class Goo { partial $$ }"); } [WorkItem(578750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578750")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttribute() { await VerifyKeywordAsync(@" class Goo { [Attr] $$ }"); } [Theory] [CombinatorialData] [WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task TestLocalFunction(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory] [CombinatorialData] [WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction2(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"unsafe $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory] [CombinatorialData] [WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction3(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"unsafe $$ void L() { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory] [CombinatorialData] [WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction4(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$ void L() { }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact] [WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction5() { await VerifyKeywordAsync(@" class Goo { public void M(Action<int> a) { M(async () => { $$ }); } }"); } [Theory] [CombinatorialData] [WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction6(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"int $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory] [CombinatorialData] [WorkItem(8616, "https://github.com/dotnet/roslyn/issues/8616")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction7(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Portable/Symbols/FieldSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a field in a class, struct or enum /// </summary> internal abstract partial class FieldSymbol : Symbol, IFieldSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! internal FieldSymbol() { } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual FieldSymbol OriginalDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// Gets the type of this field along with its annotations. /// </summary> public TypeWithAnnotations TypeWithAnnotations { get { return GetFieldType(ConsList<FieldSymbol>.Empty); } } public abstract FlowAnalysisAnnotations FlowAnalysisAnnotations { get; } /// <summary> /// Gets the type of this field. /// </summary> public TypeSymbol Type => TypeWithAnnotations.Type; internal abstract TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound); /// <summary> /// If this field serves as a backing variable for an automatically generated /// property or a field-like event, returns that /// property/event. Otherwise returns null. /// Note, the set of possible associated symbols might be expanded in the future to /// reflect changes in the languages. /// </summary> public abstract Symbol AssociatedSymbol { get; } /// <summary> /// Returns true if this field was declared as "readonly". /// </summary> public abstract bool IsReadOnly { get; } /// <summary> /// Returns true if this field was declared as "volatile". /// </summary> public abstract bool IsVolatile { get; } /// <summary> /// Returns true if this symbol requires an instance reference as the implicit receiver. This is false if the symbol is static. /// </summary> public virtual bool RequiresInstanceReceiver => !IsStatic; /// <summary> /// Returns true if this field was declared as "fixed". /// Note that for a fixed-size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> public virtual bool IsFixedSizeBuffer { get { return false; } } /// <summary> /// If IsFixedSizeBuffer is true, the value between brackets in the fixed-size-buffer declaration. /// If IsFixedSizeBuffer is false FixedSize is 0. /// Note that for fixed-a size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> public virtual int FixedSize { get { return 0; } } /// <summary> /// If this.IsFixedSizeBuffer is true, returns the underlying implementation type for the /// fixed-size buffer when emitted. Otherwise returns null. /// </summary> internal virtual NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) { return null; } /// <summary> /// Returns true when field is a backing field for a captured frame pointer (typically "this"). /// </summary> internal virtual bool IsCapturedFrame { get { return false; } } /// <summary> /// Returns true if this field was declared as "const" (i.e. is a constant declaration). /// Also returns true for an enum member. /// </summary> public abstract bool IsConst { get; } // Gets a value indicating whether this instance is metadata constant. A constant field is considered to be // metadata constant unless they are of type decimal, because decimals are not regarded as constant by the CLR. public bool IsMetadataConstant { get { return this.IsConst && (this.Type.SpecialType != SpecialType.System_Decimal); } } /// <summary> /// Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous. /// True otherwise. /// </summary> public virtual bool HasConstantValue { get { if (!IsConst) { return false; } ConstantValue constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); return constantValue != null && !constantValue.IsBad; //can be null in error scenarios } } /// <summary> /// If IsConst returns true, then returns the constant value of the field or enum member. If IsConst returns /// false, then returns null. /// </summary> public virtual object ConstantValue { get { if (!IsConst) { return null; } ConstantValue constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); return constantValue == null ? null : constantValue.Value; //can be null in error scenarios } } internal abstract ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes); /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Field; } } internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitField(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitField(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitField(this); } /// <summary> /// Returns false because field can't be abstract. /// </summary> public sealed override bool IsAbstract { get { return false; } } /// <summary> /// Returns false because field can't be defined externally. /// </summary> public sealed override bool IsExtern { get { return false; } } /// <summary> /// Returns false because field can't be overridden. /// </summary> public sealed override bool IsOverride { get { return false; } } /// <summary> /// Returns false because field can't be sealed. /// </summary> public sealed override bool IsSealed { get { return false; } } /// <summary> /// Returns false because field can't be virtual. /// </summary> public sealed override bool IsVirtual { get { return false; } } /// <summary> /// True if this symbol has a special name (metadata flag SpecialName is set). /// </summary> internal abstract bool HasSpecialName { get; } /// <summary> /// True if this symbol has a runtime-special name (metadata flag RuntimeSpecialName is set). /// </summary> internal abstract bool HasRuntimeSpecialName { get; } /// <summary> /// True if this field is not serialized (metadata flag NotSerialized is set). /// </summary> internal abstract bool IsNotSerialized { get; } /// <summary> /// True if this field has a pointer type. /// </summary> /// <remarks> /// By default we defer to this.Type.IsPointerOrFunctionPointer() /// However in some cases this may cause circular dependency via binding a /// pointer that points to the type that contains the current field. /// Fortunately in those cases we do not need to force binding of the field's type /// and can just check the declaration syntax if the field type is not yet known. /// </remarks> internal virtual bool HasPointerType { get { return this.Type.IsPointerOrFunctionPointer(); } } /// <summary> /// Describes how the field is marshalled when passed to native code. /// Null if no specific marshalling information is available for the field. /// </summary> /// <remarks>PE symbols don't provide this information and always return null.</remarks> internal abstract MarshalPseudoCustomAttributeData MarshallingInformation { get; } /// <summary> /// Returns the marshalling type of this field, or 0 if marshalling information isn't available. /// </summary> /// <remarks> /// By default this information is extracted from <see cref="MarshallingInformation"/> if available. /// Since the compiler does only need to know the marshalling type of symbols that aren't emitted /// PE symbols just decode the type from metadata and don't provide full marshalling information. /// </remarks> internal virtual UnmanagedType MarshallingType { get { var info = MarshallingInformation; return info != null ? info.UnmanagedType : 0; } } /// <summary> /// Offset assigned to the field when the containing type is laid out by the VM. /// Null if unspecified. /// </summary> internal abstract int? TypeLayoutOffset { get; } internal virtual FieldSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition)); return newOwner.IsDefinition ? this : new SubstitutedFieldSymbol(newOwner as SubstitutedNamedTypeSymbol, this); } #region Use-Site Diagnostics internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { if (this.IsDefinition) { return new UseSiteInfo<AssemblySymbol>(PrimaryDependency); } return this.OriginalDefinition.GetUseSiteInfo(); } internal bool CalculateUseSiteDiagnostic(ref UseSiteInfo<AssemblySymbol> result) { Debug.Assert(IsDefinition); // Check type, custom modifiers if (DeriveUseSiteInfoFromType(ref result, this.TypeWithAnnotations, AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile)) { return true; } // If the member is in an assembly with unified references, // we check if its definition depends on a type from a unified reference. if (this.ContainingModule.HasUnifiedReferences) { HashSet<TypeSymbol> unificationCheckedTypes = null; DiagnosticInfo diagnosticInfo = result.DiagnosticInfo; if (this.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref diagnosticInfo, this, ref unificationCheckedTypes)) { result = result.AdjustDiagnosticInfo(diagnosticInfo); return true; } result = result.AdjustDiagnosticInfo(diagnosticInfo); } return false; } /// <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_BindToBogus; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo; return (object)info != null && info.Code == (int)ErrorCode.ERR_BindToBogus; } } #endregion /// <summary> /// Returns True when field symbol is not mapped directly to a field in the underlying tuple struct. /// </summary> public virtual bool IsVirtualTupleField { get { return false; } } /// <summary> /// Returns true if this is a field representing a Default element like Item1, Item2... /// </summary> public virtual bool IsDefaultTupleElement { get { Debug.Assert(!(this is TupleElementFieldSymbol or TupleErrorFieldSymbol)); return TupleElementIndex >= 0; } } public virtual bool IsExplicitlyNamedTupleElement { get { Debug.Assert(!(this is TupleElementFieldSymbol or TupleErrorFieldSymbol)); return false; } } /// <summary> /// If this is a field of a tuple type, return corresponding underlying field from the /// tuple underlying type. Otherwise, null. In case of a malformed underlying type /// the corresponding underlying field might be missing, return null in this case too. /// </summary> public virtual FieldSymbol TupleUnderlyingField { get { Debug.Assert(!(this is TupleElementFieldSymbol)); return ContainingType.IsTupleType ? this : null; } } /// <summary> /// If this field represents a tuple element, returns a corresponding default element field. /// Otherwise returns null. /// </summary> public virtual FieldSymbol CorrespondingTupleField { get { Debug.Assert(!(this is TupleElementFieldSymbol)); return TupleElementIndex >= 0 ? this : null; } } /// <summary> /// Returns true if a given field is a tuple element /// </summary> internal bool IsTupleElement() { return this.CorrespondingTupleField is object; } /// <summary> /// If this is a field representing a tuple element, /// returns the index of the element (zero-based). /// Otherwise returns -1 /// </summary> public virtual int TupleElementIndex { get { // wrapped tuple fields already have this information and override this property Debug.Assert(!(this is TupleElementFieldSymbol or TupleErrorFieldSymbol)); var map = ContainingType.TupleFieldDefinitionsToIndexMap; if (map is object && map.TryGetValue(this.OriginalDefinition, out int index)) { return index; } return -1; } } bool IFieldSymbolInternal.IsVolatile => this.IsVolatile; protected override ISymbol CreateISymbol() { return new PublicModel.FieldSymbol(this); } public override bool Equals(Symbol other, TypeCompareKind compareKind) { if (other is SubstitutedFieldSymbol sfs) { return sfs.Equals(this, compareKind); } return base.Equals(other, compareKind); } public override int GetHashCode() { return base.GetHashCode(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a field in a class, struct or enum /// </summary> internal abstract partial class FieldSymbol : Symbol, IFieldSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! internal FieldSymbol() { } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public new virtual FieldSymbol OriginalDefinition { get { return this; } } protected sealed override Symbol OriginalSymbolDefinition { get { return this.OriginalDefinition; } } /// <summary> /// Gets the type of this field along with its annotations. /// </summary> public TypeWithAnnotations TypeWithAnnotations { get { return GetFieldType(ConsList<FieldSymbol>.Empty); } } public abstract FlowAnalysisAnnotations FlowAnalysisAnnotations { get; } /// <summary> /// Gets the type of this field. /// </summary> public TypeSymbol Type => TypeWithAnnotations.Type; internal abstract TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound); /// <summary> /// If this field serves as a backing variable for an automatically generated /// property or a field-like event, returns that /// property/event. Otherwise returns null. /// Note, the set of possible associated symbols might be expanded in the future to /// reflect changes in the languages. /// </summary> public abstract Symbol AssociatedSymbol { get; } /// <summary> /// Returns true if this field was declared as "readonly". /// </summary> public abstract bool IsReadOnly { get; } /// <summary> /// Returns true if this field was declared as "volatile". /// </summary> public abstract bool IsVolatile { get; } /// <summary> /// Returns true if this symbol requires an instance reference as the implicit receiver. This is false if the symbol is static. /// </summary> public virtual bool RequiresInstanceReceiver => !IsStatic; /// <summary> /// Returns true if this field was declared as "fixed". /// Note that for a fixed-size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> public virtual bool IsFixedSizeBuffer { get { return false; } } /// <summary> /// If IsFixedSizeBuffer is true, the value between brackets in the fixed-size-buffer declaration. /// If IsFixedSizeBuffer is false FixedSize is 0. /// Note that for fixed-a size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> public virtual int FixedSize { get { return 0; } } /// <summary> /// If this.IsFixedSizeBuffer is true, returns the underlying implementation type for the /// fixed-size buffer when emitted. Otherwise returns null. /// </summary> internal virtual NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) { return null; } /// <summary> /// Returns true when field is a backing field for a captured frame pointer (typically "this"). /// </summary> internal virtual bool IsCapturedFrame { get { return false; } } /// <summary> /// Returns true if this field was declared as "const" (i.e. is a constant declaration). /// Also returns true for an enum member. /// </summary> public abstract bool IsConst { get; } // Gets a value indicating whether this instance is metadata constant. A constant field is considered to be // metadata constant unless they are of type decimal, because decimals are not regarded as constant by the CLR. public bool IsMetadataConstant { get { return this.IsConst && (this.Type.SpecialType != SpecialType.System_Decimal); } } /// <summary> /// Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous. /// True otherwise. /// </summary> public virtual bool HasConstantValue { get { if (!IsConst) { return false; } ConstantValue constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); return constantValue != null && !constantValue.IsBad; //can be null in error scenarios } } /// <summary> /// If IsConst returns true, then returns the constant value of the field or enum member. If IsConst returns /// false, then returns null. /// </summary> public virtual object ConstantValue { get { if (!IsConst) { return null; } ConstantValue constantValue = GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); return constantValue == null ? null : constantValue.Value; //can be null in error scenarios } } internal abstract ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes); /// <summary> /// Gets the kind of this symbol. /// </summary> public sealed override SymbolKind Kind { get { return SymbolKind.Field; } } internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument) { return visitor.VisitField(this, argument); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitField(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitField(this); } /// <summary> /// Returns false because field can't be abstract. /// </summary> public sealed override bool IsAbstract { get { return false; } } /// <summary> /// Returns false because field can't be defined externally. /// </summary> public sealed override bool IsExtern { get { return false; } } /// <summary> /// Returns false because field can't be overridden. /// </summary> public sealed override bool IsOverride { get { return false; } } /// <summary> /// Returns false because field can't be sealed. /// </summary> public sealed override bool IsSealed { get { return false; } } /// <summary> /// Returns false because field can't be virtual. /// </summary> public sealed override bool IsVirtual { get { return false; } } /// <summary> /// True if this symbol has a special name (metadata flag SpecialName is set). /// </summary> internal abstract bool HasSpecialName { get; } /// <summary> /// True if this symbol has a runtime-special name (metadata flag RuntimeSpecialName is set). /// </summary> internal abstract bool HasRuntimeSpecialName { get; } /// <summary> /// True if this field is not serialized (metadata flag NotSerialized is set). /// </summary> internal abstract bool IsNotSerialized { get; } /// <summary> /// True if this field has a pointer type. /// </summary> /// <remarks> /// By default we defer to this.Type.IsPointerOrFunctionPointer() /// However in some cases this may cause circular dependency via binding a /// pointer that points to the type that contains the current field. /// Fortunately in those cases we do not need to force binding of the field's type /// and can just check the declaration syntax if the field type is not yet known. /// </remarks> internal virtual bool HasPointerType { get { return this.Type.IsPointerOrFunctionPointer(); } } /// <summary> /// Describes how the field is marshalled when passed to native code. /// Null if no specific marshalling information is available for the field. /// </summary> /// <remarks>PE symbols don't provide this information and always return null.</remarks> internal abstract MarshalPseudoCustomAttributeData MarshallingInformation { get; } /// <summary> /// Returns the marshalling type of this field, or 0 if marshalling information isn't available. /// </summary> /// <remarks> /// By default this information is extracted from <see cref="MarshallingInformation"/> if available. /// Since the compiler does only need to know the marshalling type of symbols that aren't emitted /// PE symbols just decode the type from metadata and don't provide full marshalling information. /// </remarks> internal virtual UnmanagedType MarshallingType { get { var info = MarshallingInformation; return info != null ? info.UnmanagedType : 0; } } /// <summary> /// Offset assigned to the field when the containing type is laid out by the VM. /// Null if unspecified. /// </summary> internal abstract int? TypeLayoutOffset { get; } internal virtual FieldSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(this.IsDefinition); Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol.OriginalDefinition)); return newOwner.IsDefinition ? this : new SubstitutedFieldSymbol(newOwner as SubstitutedNamedTypeSymbol, this); } #region Use-Site Diagnostics internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { if (this.IsDefinition) { return new UseSiteInfo<AssemblySymbol>(PrimaryDependency); } return this.OriginalDefinition.GetUseSiteInfo(); } internal bool CalculateUseSiteDiagnostic(ref UseSiteInfo<AssemblySymbol> result) { Debug.Assert(IsDefinition); // Check type, custom modifiers if (DeriveUseSiteInfoFromType(ref result, this.TypeWithAnnotations, AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile)) { return true; } // If the member is in an assembly with unified references, // we check if its definition depends on a type from a unified reference. if (this.ContainingModule.HasUnifiedReferences) { HashSet<TypeSymbol> unificationCheckedTypes = null; DiagnosticInfo diagnosticInfo = result.DiagnosticInfo; if (this.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref diagnosticInfo, this, ref unificationCheckedTypes)) { result = result.AdjustDiagnosticInfo(diagnosticInfo); return true; } result = result.AdjustDiagnosticInfo(diagnosticInfo); } return false; } /// <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_BindToBogus; } } public sealed override bool HasUnsupportedMetadata { get { DiagnosticInfo info = GetUseSiteInfo().DiagnosticInfo; return (object)info != null && info.Code == (int)ErrorCode.ERR_BindToBogus; } } #endregion /// <summary> /// Returns True when field symbol is not mapped directly to a field in the underlying tuple struct. /// </summary> public virtual bool IsVirtualTupleField { get { return false; } } /// <summary> /// Returns true if this is a field representing a Default element like Item1, Item2... /// </summary> public virtual bool IsDefaultTupleElement { get { Debug.Assert(!(this is TupleElementFieldSymbol or TupleErrorFieldSymbol)); return TupleElementIndex >= 0; } } public virtual bool IsExplicitlyNamedTupleElement { get { Debug.Assert(!(this is TupleElementFieldSymbol or TupleErrorFieldSymbol)); return false; } } /// <summary> /// If this is a field of a tuple type, return corresponding underlying field from the /// tuple underlying type. Otherwise, null. In case of a malformed underlying type /// the corresponding underlying field might be missing, return null in this case too. /// </summary> public virtual FieldSymbol TupleUnderlyingField { get { Debug.Assert(!(this is TupleElementFieldSymbol)); return ContainingType.IsTupleType ? this : null; } } /// <summary> /// If this field represents a tuple element, returns a corresponding default element field. /// Otherwise returns null. /// </summary> public virtual FieldSymbol CorrespondingTupleField { get { Debug.Assert(!(this is TupleElementFieldSymbol)); return TupleElementIndex >= 0 ? this : null; } } /// <summary> /// Returns true if a given field is a tuple element /// </summary> internal bool IsTupleElement() { return this.CorrespondingTupleField is object; } /// <summary> /// If this is a field representing a tuple element, /// returns the index of the element (zero-based). /// Otherwise returns -1 /// </summary> public virtual int TupleElementIndex { get { // wrapped tuple fields already have this information and override this property Debug.Assert(!(this is TupleElementFieldSymbol or TupleErrorFieldSymbol)); var map = ContainingType.TupleFieldDefinitionsToIndexMap; if (map is object && map.TryGetValue(this.OriginalDefinition, out int index)) { return index; } return -1; } } bool IFieldSymbolInternal.IsVolatile => this.IsVolatile; protected override ISymbol CreateISymbol() { return new PublicModel.FieldSymbol(this); } public override bool Equals(Symbol other, TypeCompareKind compareKind) { if (other is SubstitutedFieldSymbol sfs) { return sfs.Equals(this, compareKind); } return base.Equals(other, compareKind); } public override int GetHashCode() { return base.GetHashCode(); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/CSharp/Portable/SignatureHelp/SignatureHelpUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal static class SignatureHelpUtilities { private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListOpenToken = list => list.GetOpenToken(); private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListOpenToken = list => list.LessThanToken; private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionOpenToken = e => e.OpenBraceToken; private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListOpenToken = list => list.OpenParenToken; private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListCloseToken = list => list.GetCloseToken(); private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListCloseToken = list => list.GreaterThanToken; private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionCloseToken = e => e.CloseBraceToken; private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListCloseToken = list => list.CloseParenToken; private static readonly Func<BaseArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getBaseArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<TypeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getTypeArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<InitializerExpressionSyntax, IEnumerable<SyntaxNodeOrToken>> s_getInitializerExpressionArgumentsWithSeparators = e => e.Expressions.GetWithSeparators(); private static readonly Func<AttributeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getAttributeArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<BaseArgumentListSyntax, IEnumerable<string?>> s_getBaseArgumentListNames = list => list.Arguments.Select(argument => argument.NameColon?.Name.Identifier.ValueText); private static readonly Func<TypeArgumentListSyntax, IEnumerable<string?>> s_getTypeArgumentListNames = list => list.Arguments.Select(a => (string?)null); private static readonly Func<InitializerExpressionSyntax, IEnumerable<string?>> s_getInitializerExpressionNames = e => e.Expressions.Select(a => (string?)null); private static readonly Func<AttributeArgumentListSyntax, IEnumerable<string?>> s_getAttributeArgumentListNames = list => list.Arguments.Select( argument => argument.NameColon != null ? argument.NameColon.Name.Identifier.ValueText : argument.NameEquals?.Name.Identifier.ValueText); internal static SignatureHelpState? GetSignatureHelpState(BaseArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getBaseArgumentListOpenToken, s_getBaseArgumentListCloseToken, s_getBaseArgumentListArgumentsWithSeparators, s_getBaseArgumentListNames); } internal static SignatureHelpState? GetSignatureHelpState(TypeArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getTypeArgumentListOpenToken, s_getTypeArgumentListCloseToken, s_getTypeArgumentListArgumentsWithSeparators, s_getTypeArgumentListNames); } internal static SignatureHelpState? GetSignatureHelpState(InitializerExpressionSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getInitializerExpressionOpenToken, s_getInitializerExpressionCloseToken, s_getInitializerExpressionArgumentsWithSeparators, s_getInitializerExpressionNames); } internal static SignatureHelpState? GetSignatureHelpState(AttributeArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getAttributeArgumentListOpenToken, s_getAttributeArgumentListCloseToken, s_getAttributeArgumentListArgumentsWithSeparators, s_getAttributeArgumentListNames); } internal static TextSpan GetSignatureHelpSpan(BaseArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getBaseArgumentListCloseToken); internal static TextSpan GetSignatureHelpSpan(TypeArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getTypeArgumentListCloseToken); internal static TextSpan GetSignatureHelpSpan(InitializerExpressionSyntax initializer) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(initializer, initializer.SpanStart, s_getInitializerExpressionCloseToken); internal static TextSpan GetSignatureHelpSpan(AttributeArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getAttributeArgumentListCloseToken); internal static bool IsTriggerParenOrComma<TSyntaxNode>(SyntaxToken token, Func<char, bool> isTriggerCharacter) where TSyntaxNode : SyntaxNode { // Don't dismiss if the user types ( to start a parenthesized expression or tuple // Note that the tuple initially parses as a parenthesized expression if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr)) { var parenthesizedExpr = parenExpr.WalkUpParentheses(); if (parenthesizedExpr.Parent is ArgumentSyntax) { var parent = parenthesizedExpr.Parent; var grandParent = parent.Parent; if (grandParent is ArgumentListSyntax && grandParent.Parent is TSyntaxNode) { // Argument to TSyntaxNode's argument list return true; } else { // Argument to a tuple in TSyntaxNode's argument list return grandParent is TupleExpressionSyntax && parenthesizedExpr.GetAncestor<TSyntaxNode>() != null; } } else { // Not an argument return false; } } // Don't dismiss if the user types ',' to add a member to a tuple if (token.IsKind(SyntaxKind.CommaToken) && token.Parent is TupleExpressionSyntax && token.GetAncestor<TSyntaxNode>() != null) { return true; } return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && isTriggerCharacter(token.ValueText[0]) && token.Parent is ArgumentListSyntax && token.Parent.Parent is TSyntaxNode; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal static class SignatureHelpUtilities { private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListOpenToken = list => list.GetOpenToken(); private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListOpenToken = list => list.LessThanToken; private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionOpenToken = e => e.OpenBraceToken; private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListOpenToken = list => list.OpenParenToken; private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListCloseToken = list => list.GetCloseToken(); private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListCloseToken = list => list.GreaterThanToken; private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionCloseToken = e => e.CloseBraceToken; private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListCloseToken = list => list.CloseParenToken; private static readonly Func<BaseArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getBaseArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<TypeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getTypeArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<InitializerExpressionSyntax, IEnumerable<SyntaxNodeOrToken>> s_getInitializerExpressionArgumentsWithSeparators = e => e.Expressions.GetWithSeparators(); private static readonly Func<AttributeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getAttributeArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<BaseArgumentListSyntax, IEnumerable<string?>> s_getBaseArgumentListNames = list => list.Arguments.Select(argument => argument.NameColon?.Name.Identifier.ValueText); private static readonly Func<TypeArgumentListSyntax, IEnumerable<string?>> s_getTypeArgumentListNames = list => list.Arguments.Select(a => (string?)null); private static readonly Func<InitializerExpressionSyntax, IEnumerable<string?>> s_getInitializerExpressionNames = e => e.Expressions.Select(a => (string?)null); private static readonly Func<AttributeArgumentListSyntax, IEnumerable<string?>> s_getAttributeArgumentListNames = list => list.Arguments.Select( argument => argument.NameColon != null ? argument.NameColon.Name.Identifier.ValueText : argument.NameEquals?.Name.Identifier.ValueText); internal static SignatureHelpState? GetSignatureHelpState(BaseArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getBaseArgumentListOpenToken, s_getBaseArgumentListCloseToken, s_getBaseArgumentListArgumentsWithSeparators, s_getBaseArgumentListNames); } internal static SignatureHelpState? GetSignatureHelpState(TypeArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getTypeArgumentListOpenToken, s_getTypeArgumentListCloseToken, s_getTypeArgumentListArgumentsWithSeparators, s_getTypeArgumentListNames); } internal static SignatureHelpState? GetSignatureHelpState(InitializerExpressionSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getInitializerExpressionOpenToken, s_getInitializerExpressionCloseToken, s_getInitializerExpressionArgumentsWithSeparators, s_getInitializerExpressionNames); } internal static SignatureHelpState? GetSignatureHelpState(AttributeArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getAttributeArgumentListOpenToken, s_getAttributeArgumentListCloseToken, s_getAttributeArgumentListArgumentsWithSeparators, s_getAttributeArgumentListNames); } internal static TextSpan GetSignatureHelpSpan(BaseArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getBaseArgumentListCloseToken); internal static TextSpan GetSignatureHelpSpan(TypeArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getTypeArgumentListCloseToken); internal static TextSpan GetSignatureHelpSpan(InitializerExpressionSyntax initializer) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(initializer, initializer.SpanStart, s_getInitializerExpressionCloseToken); internal static TextSpan GetSignatureHelpSpan(AttributeArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getAttributeArgumentListCloseToken); internal static bool IsTriggerParenOrComma<TSyntaxNode>(SyntaxToken token, Func<char, bool> isTriggerCharacter) where TSyntaxNode : SyntaxNode { // Don't dismiss if the user types ( to start a parenthesized expression or tuple // Note that the tuple initially parses as a parenthesized expression if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr)) { var parenthesizedExpr = parenExpr.WalkUpParentheses(); if (parenthesizedExpr.Parent is ArgumentSyntax) { var parent = parenthesizedExpr.Parent; var grandParent = parent.Parent; if (grandParent is ArgumentListSyntax && grandParent.Parent is TSyntaxNode) { // Argument to TSyntaxNode's argument list return true; } else { // Argument to a tuple in TSyntaxNode's argument list return grandParent is TupleExpressionSyntax && parenthesizedExpr.GetAncestor<TSyntaxNode>() != null; } } else { // Not an argument return false; } } // Don't dismiss if the user types ',' to add a member to a tuple if (token.IsKind(SyntaxKind.CommaToken) && token.Parent is TupleExpressionSyntax && token.GetAncestor<TSyntaxNode>() != null) { return true; } return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && isTriggerCharacter(token.ValueText[0]) && token.Parent is ArgumentListSyntax && token.Parent.Parent is TSyntaxNode; } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Portable/Symbols/Source/SourceAssemblySymbol.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.Reflection; using System.Security.Cryptography; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; using CommonAssemblyWellKnownAttributeData = Microsoft.CodeAnalysis.CommonAssemblyWellKnownAttributeData<Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol>; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an assembly built by compiler. /// </summary> internal sealed partial class SourceAssemblySymbol : MetadataOrSourceAssemblySymbol, ISourceAssemblySymbolInternal, IAttributeTargetSymbol { /// <summary> /// A Compilation the assembly is created for. /// </summary> private readonly CSharpCompilation _compilation; private SymbolCompletionState _state; /// <summary> /// Assembly's identity. /// </summary> internal AssemblyIdentity lazyAssemblyIdentity; private readonly string _assemblySimpleName; // Computing the identity requires computing the public key. Computing the public key // can require binding attributes that contain version or strong name information. // Attribute binding will check type visibility which will possibly // check IVT relationships. To correctly determine the IVT relationship requires the public key. // To avoid infinite recursion, this type notes, per thread, the assembly for which the thread // is actively computing the public key (assemblyForWhichCurrentThreadIsComputingKeys). Should a request to determine IVT // relationship occur on the thread that is computing the public key, access is optimistically // granted provided the simple assembly names match. When such access is granted // the assembly to which we have been granted access is noted (optimisticallyGrantedInternalsAccess). // After the public key has been computed, the set of optimistic grants is reexamined // to ensure that full identities match. This may produce diagnostics. private StrongNameKeys _lazyStrongNameKeys; /// <summary> /// A list of modules the assembly consists of. /// The first (index=0) module is a SourceModuleSymbol, which is a primary module, the rest are net-modules. /// </summary> private readonly ImmutableArray<ModuleSymbol> _modules; /// <summary> /// Bag of assembly's custom attributes and decoded well-known attribute data from source. /// </summary> private CustomAttributesBag<CSharpAttributeData> _lazySourceAttributesBag; /// <summary> /// Bag of assembly's custom attributes and decoded well-known attribute data from added netmodules. /// </summary> private CustomAttributesBag<CSharpAttributeData> _lazyNetModuleAttributesBag; private IDictionary<string, NamedTypeSymbol> _lazyForwardedTypesFromSource; /// <summary> /// Indices of attributes that will not be emitted for one of two reasons: /// - They are duplicates of another attribute (i.e. attributes that bind to the same constructor and have identical arguments) /// - They are InternalsVisibleToAttributes with invalid assembly identities /// </summary> /// <remarks> /// These indices correspond to the merged assembly attributes from source and added net modules, i.e. attributes returned by <see cref="GetAttributes"/> method. /// </remarks> private ConcurrentSet<int> _lazyOmittedAttributeIndices; private ThreeState _lazyContainsExtensionMethods; /// <summary> /// Map for storing effectively private or effectively internal fields declared in this assembly but never initialized nor assigned. /// Each {symbol, bool} key-value pair in this map indicates the following: /// (a) Key: Unassigned field symbol. /// (b) Value: True if the unassigned field is effectively internal, false otherwise. /// </summary> private readonly ConcurrentDictionary<FieldSymbol, bool> _unassignedFieldsMap = new ConcurrentDictionary<FieldSymbol, bool>(); /// <summary> /// private fields declared in this assembly but never read /// </summary> private readonly ConcurrentSet<FieldSymbol> _unreadFields = new ConcurrentSet<FieldSymbol>(); /// <summary> /// We imitate the native compiler's policy of not warning about unused fields /// when the enclosing type is used by an extern method for a ref argument. /// Here we keep track of those types. /// </summary> internal ConcurrentSet<TypeSymbol> TypesReferencedInExternalMethods = new ConcurrentSet<TypeSymbol>(); /// <summary> /// The warnings for unused fields. /// </summary> private ImmutableArray<Diagnostic> _unusedFieldWarnings; internal SourceAssemblySymbol( CSharpCompilation compilation, string assemblySimpleName, string moduleName, ImmutableArray<PEModule> netModules) { Debug.Assert(compilation != null); Debug.Assert(assemblySimpleName != null); Debug.Assert(!String.IsNullOrWhiteSpace(moduleName)); Debug.Assert(!netModules.IsDefault); _compilation = compilation; _assemblySimpleName = assemblySimpleName; ArrayBuilder<ModuleSymbol> moduleBuilder = new ArrayBuilder<ModuleSymbol>(1 + netModules.Length); moduleBuilder.Add(new SourceModuleSymbol(this, compilation.Declarations, moduleName)); var importOptions = (compilation.Options.MetadataImportOptions == MetadataImportOptions.All) ? MetadataImportOptions.All : MetadataImportOptions.Internal; foreach (PEModule netModule in netModules) { moduleBuilder.Add(new PEModuleSymbol(this, netModule, importOptions, moduleBuilder.Count)); // SetReferences will be called later by the ReferenceManager (in CreateSourceAssemblyFullBind for // a fresh manager, in CreateSourceAssemblyReuseData for a reused one). } _modules = moduleBuilder.ToImmutableAndFree(); if (!compilation.Options.CryptoPublicKey.IsEmpty) { // Private key is not necessary for assembly identity, only when emitting. For this reason, the private key can remain null. _lazyStrongNameKeys = StrongNameKeys.Create(compilation.Options.CryptoPublicKey, privateKey: null, hasCounterSignature: false, MessageProvider.Instance); } } public override string Name { get { return _assemblySimpleName; } } /// <remarks> /// This override is essential - it's a base case of the recursive definition. /// </remarks> internal sealed override CSharpCompilation DeclaringCompilation { get { return _compilation; } } public override bool IsInteractive { get { return _compilation.IsSubmission; } } internal bool MightContainNoPiaLocalTypes() { for (int i = 1; i < _modules.Length; i++) { var peModuleSymbol = (Metadata.PE.PEModuleSymbol)_modules[i]; if (peModuleSymbol.Module.ContainsNoPiaLocalTypes()) { return true; } } return SourceModule.MightContainNoPiaLocalTypes(); } public override AssemblyIdentity Identity { get { if (lazyAssemblyIdentity == null) Interlocked.CompareExchange(ref lazyAssemblyIdentity, ComputeIdentity(), null); return lazyAssemblyIdentity; } } internal override Symbol GetSpecialTypeMember(SpecialMember member) { return _compilation.IsMemberMissing(member) ? null : base.GetSpecialTypeMember(member); } #nullable enable private string? GetWellKnownAttributeDataStringField(Func<CommonAssemblyWellKnownAttributeData, string> fieldGetter, string? missingValue = null, QuickAttributes? attributeMatchesOpt = null) { string? fieldValue = missingValue; var data = attributeMatchesOpt is null ? GetSourceDecodedWellKnownAttributeData() : GetSourceDecodedWellKnownAttributeData(attributeMatchesOpt.Value); if (data != null) { fieldValue = fieldGetter(data); } if (fieldValue == (object?)missingValue) { data = (attributeMatchesOpt is null || _lazyNetModuleAttributesBag is not null) ? GetNetModuleDecodedWellKnownAttributeData() : GetLimitedNetModuleDecodedWellKnownAttributeData(attributeMatchesOpt.Value); if (data != null) { fieldValue = fieldGetter(data); } } return fieldValue; } #nullable disable internal bool RuntimeCompatibilityWrapNonExceptionThrows { get { var data = GetSourceDecodedWellKnownAttributeData() ?? GetNetModuleDecodedWellKnownAttributeData(); // By default WrapNonExceptionThrows is considered to be true. return (data != null) ? data.RuntimeCompatibilityWrapNonExceptionThrows : CommonAssemblyWellKnownAttributeData.WrapNonExceptionThrowsDefault; } } internal string FileVersion { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyFileVersionAttributeSetting); } } internal string Title { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyTitleAttributeSetting); } } internal string Description { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyDescriptionAttributeSetting); } } internal string Company { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyCompanyAttributeSetting); } } internal string Product { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyProductAttributeSetting); } } internal string InformationalVersion { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyInformationalVersionAttributeSetting); } } internal string Copyright { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyCopyrightAttributeSetting); } } internal string Trademark { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyTrademarkAttributeSetting); } } private ThreeState AssemblyDelaySignAttributeSetting { get { var defaultValue = ThreeState.Unknown; var fieldValue = defaultValue; var data = GetSourceDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyDelaySignAttributeSetting; } if (fieldValue == defaultValue) { data = GetNetModuleDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyDelaySignAttributeSetting; } } return fieldValue; } } private string AssemblyKeyContainerAttributeSetting { get { // We mitigate circularity problems by only actively loading attributes that pass a syntactic check return GetWellKnownAttributeDataStringField(data => data.AssemblyKeyContainerAttributeSetting, WellKnownAttributeData.StringMissingValue, QuickAttributes.AssemblyKeyName); } } private string AssemblyKeyFileAttributeSetting { get { // We mitigate circularity problems by only actively loading attributes that pass a syntactic check return GetWellKnownAttributeDataStringField(data => data.AssemblyKeyFileAttributeSetting, WellKnownAttributeData.StringMissingValue, QuickAttributes.AssemblyKeyFile); } } private string AssemblyCultureAttributeSetting { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyCultureAttributeSetting); } } public string SignatureKey { get { // We mitigate circularity problems by only actively loading attributes that pass a syntactic check return GetWellKnownAttributeDataStringField(data => data.AssemblySignatureKeyAttributeSetting, missingValue: null, QuickAttributes.AssemblySignatureKey); } } private Version AssemblyVersionAttributeSetting { get { var defaultValue = (Version)null; var fieldValue = defaultValue; var data = GetSourceDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyVersionAttributeSetting; } if (fieldValue == defaultValue) { data = GetNetModuleDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyVersionAttributeSetting; } } return fieldValue; } } public override Version AssemblyVersionPattern { get { var attributeValue = AssemblyVersionAttributeSetting; return (object)attributeValue == null || (attributeValue.Build != ushort.MaxValue && attributeValue.Revision != ushort.MaxValue) ? null : attributeValue; } } public AssemblyHashAlgorithm HashAlgorithm { get { return AssemblyAlgorithmIdAttributeSetting ?? AssemblyHashAlgorithm.Sha1; } } internal AssemblyHashAlgorithm? AssemblyAlgorithmIdAttributeSetting { get { var fieldValue = (AssemblyHashAlgorithm?)null; var data = GetSourceDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyAlgorithmIdAttributeSetting; } if (!fieldValue.HasValue) { data = GetNetModuleDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyAlgorithmIdAttributeSetting; } } return fieldValue; } } /// <summary> /// This represents what the user claimed in source through the AssemblyFlagsAttribute. /// It may be modified as emitted due to presence or absence of the public key. /// </summary> public AssemblyFlags AssemblyFlags { get { var defaultValue = default(AssemblyFlags); var fieldValue = defaultValue; var data = GetSourceDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyFlagsAttributeSetting; } data = GetNetModuleDecodedWellKnownAttributeData(); if (data != null) { fieldValue |= data.AssemblyFlagsAttributeSetting; } return fieldValue; } } private StrongNameKeys ComputeStrongNameKeys() { // when both attributes and command-line options specified, cmd line wins. string keyFile = _compilation.Options.CryptoKeyFile; // Public sign requires a keyfile if (DeclaringCompilation.Options.PublicSign) { // TODO(https://github.com/dotnet/roslyn/issues/9150): // Provide better error message if keys are provided by // the attributes. Right now we'll just fall through to the // "no key available" error. if (!string.IsNullOrEmpty(keyFile) && !PathUtilities.IsAbsolute(keyFile)) { // If keyFile has a relative path then there should be a diagnostic // about it Debug.Assert(!DeclaringCompilation.Options.Errors.IsEmpty); return StrongNameKeys.None; } // If we're public signing, we don't need a strong name provider return StrongNameKeys.Create(keyFile, MessageProvider.Instance); } if (string.IsNullOrEmpty(keyFile)) { keyFile = this.AssemblyKeyFileAttributeSetting; if ((object)keyFile == (object)WellKnownAttributeData.StringMissingValue) { keyFile = null; } } string keyContainer = _compilation.Options.CryptoKeyContainer; if (string.IsNullOrEmpty(keyContainer)) { keyContainer = this.AssemblyKeyContainerAttributeSetting; if ((object)keyContainer == (object)WellKnownAttributeData.StringMissingValue) { keyContainer = null; } } var hasCounterSignature = !string.IsNullOrEmpty(this.SignatureKey); return StrongNameKeys.Create(DeclaringCompilation.Options.StrongNameProvider, keyFile, keyContainer, hasCounterSignature, MessageProvider.Instance); } // A collection of assemblies to which we were granted internals access by only checking matches for assembly name // and ignoring public key. This just acts as a set. The bool is ignored. private ConcurrentDictionary<AssemblySymbol, bool> _optimisticallyGrantedInternalsAccess; //EDMAURER please don't use thread local storage widely. This is hoped to be a one-off usage. [ThreadStatic] private static AssemblySymbol t_assemblyForWhichCurrentThreadIsComputingKeys; internal StrongNameKeys StrongNameKeys { get { if (_lazyStrongNameKeys == null) { try { t_assemblyForWhichCurrentThreadIsComputingKeys = this; Interlocked.CompareExchange(ref _lazyStrongNameKeys, ComputeStrongNameKeys(), null); } finally { t_assemblyForWhichCurrentThreadIsComputingKeys = null; } } return _lazyStrongNameKeys; } } internal override ImmutableArray<byte> PublicKey { get { return StrongNameKeys.PublicKey; } } public override ImmutableArray<ModuleSymbol> Modules { get { return _modules; } } //TODO: cache public override ImmutableArray<Location> Locations { get { return this.Modules.SelectMany(m => m.Locations).AsImmutable(); } } private void ValidateAttributeSemantics(BindingDiagnosticBag diagnostics) { //diagnostics that come from computing the public key. //If building a netmodule, strong name keys need not be validated. Dev11 didn't. if (StrongNameKeys.DiagnosticOpt != null && !_compilation.Options.OutputKind.IsNetModule()) { diagnostics.Add(StrongNameKeys.DiagnosticOpt); } ValidateIVTPublicKeys(diagnostics); //diagnostics that result from IVT checks performed while in the process of computing the public key. CheckOptimisticIVTAccessGrants(diagnostics); DetectAttributeAndOptionConflicts(diagnostics); if (IsDelaySigned && !Identity.HasPublicKey) { diagnostics.Add(ErrorCode.WRN_DelaySignButNoKey, NoLocation.Singleton); } if (DeclaringCompilation.Options.PublicSign) { if (_compilation.Options.OutputKind.IsNetModule()) { diagnostics.Add(ErrorCode.ERR_PublicSignNetModule, NoLocation.Singleton); } else if (!Identity.HasPublicKey) { diagnostics.Add(ErrorCode.ERR_PublicSignButNoKey, NoLocation.Singleton); } } // If the options and attributes applied on the compilation imply real signing, // but we have no private key to sign it with report an error. // Note that if public key is set and delay sign is off we do OSS signing, which doesn't require private key. // Consider: should we allow to OSS sign if the key file only contains public key? if (DeclaringCompilation.Options.OutputKind != OutputKind.NetModule && DeclaringCompilation.Options.CryptoPublicKey.IsEmpty && Identity.HasPublicKey && !IsDelaySigned && !DeclaringCompilation.Options.PublicSign && !StrongNameKeys.CanSign && StrongNameKeys.DiagnosticOpt == null) { // Since the container always contains both keys, the problem is that the key file didn't contain private key. diagnostics.Add(ErrorCode.ERR_SignButNoPrivateKey, NoLocation.Singleton, StrongNameKeys.KeyFilePath); } ReportDiagnosticsForSynthesizedAttributes(_compilation, diagnostics); } /// <summary> /// We're going to synthesize some well-known attributes for this assembly symbol. However, at synthesis time, it is /// too late to report diagnostics or cancel the emit. Instead, we check for use site errors on the types and members /// we know we'll need at synthesis time. /// </summary> /// <remarks> /// As in Dev10, we won't report anything if the attribute TYPES are missing (note: missing, not erroneous) because we won't /// synthesize anything in that case. We'll only report diagnostics if the attribute TYPES are present and either they or /// the attribute CONSTRUCTORS have errors. /// </remarks> private static void ReportDiagnosticsForSynthesizedAttributes(CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { ReportDiagnosticsForUnsafeSynthesizedAttributes(compilation, diagnostics); CSharpCompilationOptions compilationOptions = compilation.Options; if (!compilationOptions.OutputKind.IsNetModule()) { TypeSymbol compilationRelaxationsAttribute = compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute); Debug.Assert((object)compilationRelaxationsAttribute != null, "GetWellKnownType unexpectedly returned null"); if (!(compilationRelaxationsAttribute is MissingMetadataTypeSymbol)) { // As in Dev10 (see GlobalAttrBind::EmitCompilerGeneratedAttrs), we only synthesize this attribute if CompilationRelaxationsAttribute is found. Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32, diagnostics, NoLocation.Singleton); } TypeSymbol runtimeCompatibilityAttribute = compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute); Debug.Assert((object)runtimeCompatibilityAttribute != null, "GetWellKnownType unexpectedly returned null"); if (!(runtimeCompatibilityAttribute is MissingMetadataTypeSymbol)) { // As in Dev10 (see GlobalAttrBind::EmitCompilerGeneratedAttrs), we only synthesize this attribute if RuntimeCompatibilityAttribute is found. Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor, diagnostics, NoLocation.Singleton); Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows, diagnostics, NoLocation.Singleton); } } } /// <summary> /// If this compilation allows unsafe code (note: allows, not contains), then when we actually emit the assembly/module, /// we're going to synthesize SecurityPermissionAttribute/UnverifiableCodeAttribute. However, at synthesis time, it is /// too late to report diagnostics or cancel the emit. Instead, we check for use site errors on the types and members /// we know we'll need at synthesis time. /// </summary> /// <remarks> /// As in Dev10, we won't report anything if the attribute TYPES are missing (note: missing, not erroneous) because we won't /// synthesize anything in that case. We'll only report diagnostics if the attribute TYPES are present and either they or /// the attribute CONSTRUCTORS have errors. /// </remarks> private static void ReportDiagnosticsForUnsafeSynthesizedAttributes(CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { CSharpCompilationOptions compilationOptions = compilation.Options; if (!compilationOptions.AllowUnsafe) { return; } TypeSymbol unverifiableCodeAttribute = compilation.GetWellKnownType(WellKnownType.System_Security_UnverifiableCodeAttribute); Debug.Assert((object)unverifiableCodeAttribute != null, "GetWellKnownType unexpectedly returned null"); if (unverifiableCodeAttribute is MissingMetadataTypeSymbol) { return; } // As in Dev10 (see GlobalAttrBind::EmitCompilerGeneratedAttrs), we only synthesize this attribute if // UnverifiableCodeAttribute is found. Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Security_UnverifiableCodeAttribute__ctor, diagnostics, NoLocation.Singleton); TypeSymbol securityPermissionAttribute = compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityPermissionAttribute); Debug.Assert((object)securityPermissionAttribute != null, "GetWellKnownType unexpectedly returned null"); if (securityPermissionAttribute is MissingMetadataTypeSymbol) { return; } TypeSymbol securityAction = compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction); Debug.Assert((object)securityAction != null, "GetWellKnownType unexpectedly returned null"); if (securityAction is MissingMetadataTypeSymbol) { return; } // As in Dev10 (see GlobalAttrBind::EmitCompilerGeneratedAttrs), we only synthesize this attribute if // UnverifiableCodeAttribute, SecurityAction, and SecurityPermissionAttribute are found. Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Security_Permissions_SecurityPermissionAttribute__ctor, diagnostics, NoLocation.Singleton); // Not actually an attribute, but the same logic applies. Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Security_Permissions_SecurityPermissionAttribute__SkipVerification, diagnostics, NoLocation.Singleton); } private void ValidateIVTPublicKeys(BindingDiagnosticBag diagnostics) { EnsureAttributesAreBound(); if (!this.Identity.IsStrongName) return; if (_lazyInternalsVisibleToMap != null) { foreach (var keys in _lazyInternalsVisibleToMap.Values) { foreach (var oneKey in keys) { if (oneKey.Key.IsDefaultOrEmpty) { diagnostics.Add(ErrorCode.ERR_FriendAssemblySNReq, oneKey.Value.Item1, oneKey.Value.Item2); } } } } } /// <summary> /// True if internals are exposed at all. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// This property shouldn't be accessed during binding as it can lead to attribute binding cycle. /// </remarks> public bool InternalsAreVisible { get { EnsureAttributesAreBound(); return _lazyInternalsVisibleToMap != null; } } private void DetectAttributeAndOptionConflicts(BindingDiagnosticBag diagnostics) { EnsureAttributesAreBound(); ThreeState assemblyDelaySignAttributeSetting = this.AssemblyDelaySignAttributeSetting; if (_compilation.Options.DelaySign.HasValue && (assemblyDelaySignAttributeSetting != ThreeState.Unknown) && (DeclaringCompilation.Options.DelaySign.Value != (assemblyDelaySignAttributeSetting == ThreeState.True))) { diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, NoLocation.Singleton, "DelaySign", AttributeDescription.AssemblyDelaySignAttribute.FullName); } if (_compilation.Options.PublicSign && assemblyDelaySignAttributeSetting == ThreeState.True) { diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, NoLocation.Singleton, nameof(_compilation.Options.PublicSign), AttributeDescription.AssemblyDelaySignAttribute.FullName); } if (!String.IsNullOrEmpty(_compilation.Options.CryptoKeyContainer)) { string assemblyKeyContainerAttributeSetting = this.AssemblyKeyContainerAttributeSetting; if ((object)assemblyKeyContainerAttributeSetting == (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { if (_compilation.Options.OutputKind == OutputKind.NetModule) { // We need to synthesize this attribute for .NET module, // touch the constructor in order to generate proper use-site diagnostics Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(_compilation, WellKnownMember.System_Reflection_AssemblyKeyNameAttribute__ctor, diagnostics, NoLocation.Singleton); } } else if (String.Compare(_compilation.Options.CryptoKeyContainer, assemblyKeyContainerAttributeSetting, StringComparison.OrdinalIgnoreCase) != 0) { // Native compiler reports a warning in this case, notifying the user that attribute value from source is ignored, // but it doesn't drop the attribute during emit. That might be fine if we produce an assembly because we actually sign it with correct // key (the one from compilation options) without relying on the emitted attribute. // If we are building a .NET module, things get more complicated. In particular, we don't sign the module, we emit an attribute with the key // information, which will be used to sign an assembly once the module is linked into it. If there is already an attribute like that in source, // native compiler emits both of them, synthetic attribute is emitted after the one from source. Incidentally, ALink picks the last attribute // for signing and things seem to work out. However, relying on the order of attributes feels fragile, especially given that Roslyn emits // synthetic attributes before attributes from source. The behavior we settled on for .NET modules is that, if the attribute in source has the // same value as the one in compilation options, we won't emit the synthetic attribute. If the value doesn't match, we report an error, which // is a breaking change. Bottom line, we will never produce a module or an assembly with two attributes, regardless whether values are the same // or not. if (_compilation.Options.OutputKind == OutputKind.NetModule) { diagnostics.Add(ErrorCode.ERR_CmdOptionConflictsSource, NoLocation.Singleton, AttributeDescription.AssemblyKeyNameAttribute.FullName, "CryptoKeyContainer"); } else { diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, NoLocation.Singleton, "CryptoKeyContainer", AttributeDescription.AssemblyKeyNameAttribute.FullName); } } } if (_compilation.Options.PublicSign && !_compilation.Options.OutputKind.IsNetModule() && (object)this.AssemblyKeyContainerAttributeSetting != (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { diagnostics.Add(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning, NoLocation.Singleton, AttributeDescription.AssemblyKeyNameAttribute.FullName); } if (!String.IsNullOrEmpty(_compilation.Options.CryptoKeyFile)) { string assemblyKeyFileAttributeSetting = this.AssemblyKeyFileAttributeSetting; if ((object)assemblyKeyFileAttributeSetting == (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { if (_compilation.Options.OutputKind == OutputKind.NetModule) { // We need to synthesize this attribute for .NET module, // touch the constructor in order to generate proper use-site diagnostics Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(_compilation, WellKnownMember.System_Reflection_AssemblyKeyFileAttribute__ctor, diagnostics, NoLocation.Singleton); } } else if (String.Compare(_compilation.Options.CryptoKeyFile, assemblyKeyFileAttributeSetting, StringComparison.OrdinalIgnoreCase) != 0) { // Comment in similar section for CryptoKeyContainer is applicable here as well. if (_compilation.Options.OutputKind == OutputKind.NetModule) { diagnostics.Add(ErrorCode.ERR_CmdOptionConflictsSource, NoLocation.Singleton, AttributeDescription.AssemblyKeyFileAttribute.FullName, "CryptoKeyFile"); } else { diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, NoLocation.Singleton, "CryptoKeyFile", AttributeDescription.AssemblyKeyFileAttribute.FullName); } } } if (_compilation.Options.PublicSign && !_compilation.Options.OutputKind.IsNetModule() && (object)this.AssemblyKeyFileAttributeSetting != (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { diagnostics.Add(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning, NoLocation.Singleton, AttributeDescription.AssemblyKeyFileAttribute.FullName); } } internal bool IsDelaySigned { get { //commandline setting trumps attribute value. Warning assumed to be given elsewhere if (_compilation.Options.DelaySign.HasValue) { return _compilation.Options.DelaySign.Value; } // The public sign argument should also override the attribute if (_compilation.Options.PublicSign) { return false; } return (this.AssemblyDelaySignAttributeSetting == ThreeState.True); } } internal SourceModuleSymbol SourceModule { get { return (SourceModuleSymbol)this.Modules[0]; } } internal override bool RequiresCompletion { get { return true; } } internal override bool HasComplete(CompletionPart part) { return _state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: EnsureAttributesAreBound(); break; case CompletionPart.StartAttributeChecks: case CompletionPart.FinishAttributeChecks: if (_state.NotePartComplete(CompletionPart.StartAttributeChecks)) { var diagnostics = BindingDiagnosticBag.GetInstance(); ValidateAttributeSemantics(diagnostics); AddDeclarationDiagnostics(diagnostics); var thisThreadCompleted = _state.NotePartComplete(CompletionPart.FinishAttributeChecks); Debug.Assert(thisThreadCompleted); diagnostics.Free(); } break; case CompletionPart.Module: SourceModule.ForceComplete(locationOpt, cancellationToken); if (SourceModule.HasComplete(CompletionPart.MembersCompleted)) { _state.NotePartComplete(CompletionPart.Module); break; } else { Debug.Assert(locationOpt != null, "If no location was specified, then the module members should be completed"); // this is the last completion part we can handle if there is a location. return; } case CompletionPart.StartValidatingAddedModules: case CompletionPart.FinishValidatingAddedModules: if (_state.NotePartComplete(CompletionPart.StartValidatingAddedModules)) { ReportDiagnosticsForAddedModules(); var thisThreadCompleted = _state.NotePartComplete(CompletionPart.FinishValidatingAddedModules); Debug.Assert(thisThreadCompleted); } break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(CompletionPart.All & ~CompletionPart.AssemblySymbolAll); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } } private void ReportDiagnosticsForAddedModules() { var diagnostics = BindingDiagnosticBag.GetInstance(); foreach (var pair in _compilation.GetBoundReferenceManager().ReferencedModuleIndexMap) { var fileRef = pair.Key as PortableExecutableReference; if ((object)fileRef != null && (object)fileRef.FilePath != null) { string fileName = FileNameUtilities.GetFileName(fileRef.FilePath); string moduleName = _modules[pair.Value].Name; if (!string.Equals(fileName, moduleName, StringComparison.OrdinalIgnoreCase)) { // Used to be ERR_ALinkFailed diagnostics.Add(ErrorCode.ERR_NetModuleNameMismatch, NoLocation.Singleton, moduleName, fileName); } } } // Alink performed these checks only when emitting an assembly. if (_modules.Length > 1 && !_compilation.Options.OutputKind.IsNetModule()) { var assemblyMachine = this.Machine; bool isPlatformAgnostic = (assemblyMachine == System.Reflection.PortableExecutable.Machine.I386 && !this.Bit32Required); var knownModuleNames = new HashSet<String>(StringComparer.OrdinalIgnoreCase); for (int i = 1; i < _modules.Length; i++) { ModuleSymbol m = _modules[i]; if (!knownModuleNames.Add(m.Name)) { diagnostics.Add(ErrorCode.ERR_NetModuleNameMustBeUnique, NoLocation.Singleton, m.Name); } if (!((PEModuleSymbol)m).Module.IsCOFFOnly) { var moduleMachine = m.Machine; if (moduleMachine == System.Reflection.PortableExecutable.Machine.I386 && !m.Bit32Required) { // Other module is agnostic, this is always safe ; } else if (isPlatformAgnostic) { diagnostics.Add(ErrorCode.ERR_AgnosticToMachineModule, NoLocation.Singleton, m); } else if (assemblyMachine != moduleMachine) { // Different machine types, and neither is agnostic // So it is a conflict diagnostics.Add(ErrorCode.ERR_ConflictingMachineModule, NoLocation.Singleton, m); } } } // Assembly main module must explicitly reference all the modules referenced by other assembly // modules, i.e. all modules from transitive closure must be referenced explicitly here for (int i = 1; i < _modules.Length; i++) { var m = (PEModuleSymbol)_modules[i]; try { foreach (var referencedModuleName in m.Module.GetReferencedManagedModulesOrThrow()) { // Do not report error for this module twice if (knownModuleNames.Add(referencedModuleName)) { diagnostics.Add(ErrorCode.ERR_MissingNetModuleReference, NoLocation.Singleton, referencedModuleName); } } } catch (BadImageFormatException) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, m), NoLocation.Singleton); } } } ReportNameCollisionDiagnosticsForAddedModules(this.GlobalNamespace, diagnostics); AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); } private void ReportNameCollisionDiagnosticsForAddedModules(NamespaceSymbol ns, BindingDiagnosticBag diagnostics) { var mergedNs = ns as MergedNamespaceSymbol; if ((object)mergedNs == null) { return; } ImmutableArray<NamespaceSymbol> constituent = mergedNs.ConstituentNamespaces; if (constituent.Length > 2 || (constituent.Length == 2 && constituent[0].ContainingModule.Ordinal != 0 && constituent[1].ContainingModule.Ordinal != 0)) { var topLevelTypesFromModules = ArrayBuilder<NamedTypeSymbol>.GetInstance(); foreach (var moduleNs in constituent) { Debug.Assert(moduleNs.Extent.Kind == NamespaceKind.Module); if (moduleNs.ContainingModule.Ordinal != 0) { topLevelTypesFromModules.AddRange(moduleNs.GetTypeMembers()); } } topLevelTypesFromModules.Sort(NameCollisionForAddedModulesTypeComparer.Singleton); bool reportedAnError = false; for (int i = 0; i < topLevelTypesFromModules.Count - 1; i++) { NamedTypeSymbol x = topLevelTypesFromModules[i]; NamedTypeSymbol y = topLevelTypesFromModules[i + 1]; if (x.Arity == y.Arity && x.Name == y.Name) { if (!reportedAnError) { // Skip synthetic <Module> type which every .NET module has. if (x.Arity != 0 || !x.ContainingNamespace.IsGlobalNamespace || x.Name != "<Module>") { diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, y.Locations.FirstOrNone(), y.ToDisplayString(SymbolDisplayFormat.ShortFormat), y.ContainingNamespace); } reportedAnError = true; } } else { reportedAnError = false; } } topLevelTypesFromModules.Free(); // Descent into child namespaces. foreach (Symbol member in mergedNs.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { ReportNameCollisionDiagnosticsForAddedModules((NamespaceSymbol)member, diagnostics); } } } } private class NameCollisionForAddedModulesTypeComparer : IComparer<NamedTypeSymbol> { public static readonly NameCollisionForAddedModulesTypeComparer Singleton = new NameCollisionForAddedModulesTypeComparer(); private NameCollisionForAddedModulesTypeComparer() { } public int Compare(NamedTypeSymbol x, NamedTypeSymbol y) { int result = String.CompareOrdinal(x.Name, y.Name); if (result == 0) { result = x.Arity - y.Arity; if (result == 0) { result = x.ContainingModule.Ordinal - y.ContainingModule.Ordinal; } } return result; } } private bool IsKnownAssemblyAttribute(CSharpAttributeData attribute) { // TODO: This list used to include AssemblyOperatingSystemAttribute and AssemblyProcessorAttribute, // but it doesn't look like they are defined, cannot find them on MSDN. if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTitleAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDescriptionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyConfigurationAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCultureAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCompanyAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyProductAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyInformationalVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCopyrightAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTrademarkAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyFileAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyNameAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyAlgorithmIdAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyFlagsAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDelaySignAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyFileVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.SatelliteContractVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblySignatureKeyAttribute)) { return true; } return false; } private void AddOmittedAttributeIndex(int index) { if (_lazyOmittedAttributeIndices == null) { Interlocked.CompareExchange(ref _lazyOmittedAttributeIndices, new ConcurrentSet<int>(), null); } _lazyOmittedAttributeIndices.Add(index); } /// <summary> /// Gets unique source assembly attributes that should be emitted, /// i.e. filters out attributes with errors and duplicate attributes. /// </summary> private HashSet<CSharpAttributeData> GetUniqueSourceAssemblyAttributes() { ImmutableArray<CSharpAttributeData> appliedSourceAttributes = this.GetSourceAttributesBag().Attributes; HashSet<CSharpAttributeData> uniqueAttributes = null; for (int i = 0; i < appliedSourceAttributes.Length; i++) { CSharpAttributeData attribute = appliedSourceAttributes[i]; if (!attribute.HasErrors) { if (!AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes)) { AddOmittedAttributeIndex(i); } } } return uniqueAttributes; } private static bool AddUniqueAssemblyAttribute(CSharpAttributeData attribute, ref HashSet<CSharpAttributeData> uniqueAttributes) { Debug.Assert(!attribute.HasErrors); if (uniqueAttributes == null) { uniqueAttributes = new HashSet<CSharpAttributeData>(comparer: CommonAttributeDataComparer.Instance); } return uniqueAttributes.Add(attribute); } private bool ValidateAttributeUsageForNetModuleAttribute(CSharpAttributeData attribute, string netModuleName, BindingDiagnosticBag diagnostics, ref HashSet<CSharpAttributeData> uniqueAttributes) { Debug.Assert(!attribute.HasErrors); var attributeClass = attribute.AttributeClass; if (attributeClass.GetAttributeUsageInfo().AllowMultiple) { // Duplicate attributes are allowed, but native compiler doesn't emit duplicate attributes, i.e. attributes with same constructor and arguments. return AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes); } else { // Duplicate attributes with same attribute type are not allowed. // Check if there is an existing assembly attribute with same attribute type. if (uniqueAttributes == null || !uniqueAttributes.Contains((a) => TypeSymbol.Equals(a.AttributeClass, attributeClass, TypeCompareKind.ConsiderEverything2))) { // Attribute with unique attribute type, not a duplicate. bool success = AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes); Debug.Assert(success); return true; } else { // Duplicate attribute with same attribute type, we should report an error. // Native compiler suppresses the error for // (a) Duplicate well-known assembly attributes and // (b) Identical duplicates, i.e. attributes with same constructor and arguments. // For (a), native compiler picks the last of these duplicate well-known netmodule attributes, but these can vary based on the ordering of referenced netmodules. if (IsKnownAssemblyAttribute(attribute)) { if (!uniqueAttributes.Contains(attribute)) { // This attribute application will be ignored. diagnostics.Add(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden, NoLocation.Singleton, attribute.AttributeClass, netModuleName); } } else if (AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes)) { // Error diagnostics.Add(ErrorCode.ERR_DuplicateAttributeInNetModule, NoLocation.Singleton, attribute.AttributeClass.Name, netModuleName); } return false; } } // CONSIDER Handling badly targeted assembly attributes from netmodules //if (!badDuplicateAttribute && ((attributeUsageInfo.ValidTargets & AttributeTargets.Assembly) == 0)) //{ // // Error and skip // diagnostics.Add(ErrorCode.ERR_AttributeOnBadSymbolTypeInNetModule, NoLocation.Singleton, attribute.AttributeClass.Name, netModuleName, attributeUsageInfo.GetValidTargetsString()); // return false; //} } private ImmutableArray<CSharpAttributeData> GetNetModuleAttributes(out ImmutableArray<string> netModuleNames) { ArrayBuilder<CSharpAttributeData> moduleAssemblyAttributesBuilder = null; ArrayBuilder<string> netModuleNameBuilder = null; for (int i = 1; i < _modules.Length; i++) { var peModuleSymbol = (Metadata.PE.PEModuleSymbol)_modules[i]; string netModuleName = peModuleSymbol.Name; foreach (var attributeData in peModuleSymbol.GetAssemblyAttributes()) { if (netModuleNameBuilder == null) { netModuleNameBuilder = ArrayBuilder<string>.GetInstance(); moduleAssemblyAttributesBuilder = ArrayBuilder<CSharpAttributeData>.GetInstance(); } netModuleNameBuilder.Add(netModuleName); moduleAssemblyAttributesBuilder.Add(attributeData); } } if (netModuleNameBuilder == null) { netModuleNames = ImmutableArray<string>.Empty; return ImmutableArray<CSharpAttributeData>.Empty; } netModuleNames = netModuleNameBuilder.ToImmutableAndFree(); return moduleAssemblyAttributesBuilder.ToImmutableAndFree(); } private WellKnownAttributeData ValidateAttributeUsageAndDecodeWellKnownAttributes( ImmutableArray<CSharpAttributeData> attributesFromNetModules, ImmutableArray<string> netModuleNames, BindingDiagnosticBag diagnostics) { Debug.Assert(attributesFromNetModules.Any()); Debug.Assert(netModuleNames.Any()); Debug.Assert(attributesFromNetModules.Length == netModuleNames.Length); int netModuleAttributesCount = attributesFromNetModules.Length; int sourceAttributesCount = this.GetSourceAttributesBag().Attributes.Length; // Get unique source assembly attributes. HashSet<CSharpAttributeData> uniqueAttributes = GetUniqueSourceAssemblyAttributes(); var arguments = new DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation>(); arguments.AttributesCount = netModuleAttributesCount; arguments.Diagnostics = diagnostics; arguments.SymbolPart = AttributeLocation.None; // Attributes from the second added module should override attributes from the first added module, etc. // Attributes from source should override attributes from added modules. // That is why we are iterating attributes backwards. for (int i = netModuleAttributesCount - 1; i >= 0; i--) { var totalIndex = i + sourceAttributesCount; CSharpAttributeData attribute = attributesFromNetModules[i]; if (!attribute.HasErrors && ValidateAttributeUsageForNetModuleAttribute(attribute, netModuleNames[i], diagnostics, ref uniqueAttributes)) { arguments.Attribute = attribute; arguments.Index = i; // CONSIDER: Provide usable AttributeSyntax node for diagnostics of malformed netmodule assembly attributes arguments.AttributeSyntaxOpt = null; this.DecodeWellKnownAttribute(ref arguments, totalIndex, isFromNetModule: true); } else { AddOmittedAttributeIndex(totalIndex); } } return arguments.HasDecodedData ? arguments.DecodedData : null; } private void LoadAndValidateNetModuleAttributes(ref CustomAttributesBag<CSharpAttributeData> lazyNetModuleAttributesBag) { if (_compilation.Options.OutputKind.IsNetModule()) { Interlocked.CompareExchange(ref lazyNetModuleAttributesBag, CustomAttributesBag<CSharpAttributeData>.Empty, null); } else { var diagnostics = BindingDiagnosticBag.GetInstance(); ImmutableArray<string> netModuleNames; ImmutableArray<CSharpAttributeData> attributesFromNetModules = GetNetModuleAttributes(out netModuleNames); WellKnownAttributeData wellKnownData = null; if (attributesFromNetModules.Any()) { wellKnownData = ValidateAttributeUsageAndDecodeWellKnownAttributes(attributesFromNetModules, netModuleNames, diagnostics); } else { // Compute duplicate source assembly attributes, i.e. attributes with same constructor and arguments, that must not be emitted. var unused = GetUniqueSourceAssemblyAttributes(); } // Load type forwarders from modules HashSet<NamedTypeSymbol> forwardedTypes = null; // Similar to attributes, type forwarders from the second added module should override type forwarders from the first added module, etc. // This affects only diagnostics. for (int i = _modules.Length - 1; i > 0; i--) { var peModuleSymbol = (Metadata.PE.PEModuleSymbol)_modules[i]; foreach (NamedTypeSymbol forwarded in peModuleSymbol.GetForwardedTypes()) { if (forwardedTypes == null) { if (wellKnownData == null) { wellKnownData = new CommonAssemblyWellKnownAttributeData(); } forwardedTypes = ((CommonAssemblyWellKnownAttributeData)wellKnownData).ForwardedTypes; if (forwardedTypes == null) { forwardedTypes = new HashSet<NamedTypeSymbol>(); ((CommonAssemblyWellKnownAttributeData)wellKnownData).ForwardedTypes = forwardedTypes; } } if (forwardedTypes.Add(forwarded)) { if (forwarded.IsErrorType()) { if (!diagnostics.ReportUseSite(forwarded, NoLocation.Singleton)) { DiagnosticInfo info = ((ErrorTypeSymbol)forwarded).ErrorInfo; if ((object)info != null) { diagnostics.Add(info, NoLocation.Singleton); } } } } } } CustomAttributesBag<CSharpAttributeData> netModuleAttributesBag; if (wellKnownData != null || attributesFromNetModules.Any()) { netModuleAttributesBag = new CustomAttributesBag<CSharpAttributeData>(); netModuleAttributesBag.SetEarlyDecodedWellKnownAttributeData(null); netModuleAttributesBag.SetDecodedWellKnownAttributeData(wellKnownData); netModuleAttributesBag.SetAttributes(attributesFromNetModules); if (netModuleAttributesBag.IsEmpty) netModuleAttributesBag = CustomAttributesBag<CSharpAttributeData>.Empty; } else { netModuleAttributesBag = CustomAttributesBag<CSharpAttributeData>.Empty; } if (Interlocked.CompareExchange(ref lazyNetModuleAttributesBag, netModuleAttributesBag, null) == null) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); Debug.Assert(lazyNetModuleAttributesBag.IsSealed); } } private CommonAssemblyWellKnownAttributeData GetLimitedNetModuleDecodedWellKnownAttributeData(QuickAttributes attributeMatches) { Debug.Assert(attributeMatches is QuickAttributes.AssemblyKeyFile or QuickAttributes.AssemblyKeyName or QuickAttributes.AssemblySignatureKey); if (_compilation.Options.OutputKind.IsNetModule()) { return null; } ImmutableArray<string> netModuleNames; ImmutableArray<CSharpAttributeData> attributesFromNetModules = GetNetModuleAttributes(out netModuleNames); WellKnownAttributeData wellKnownData = null; if (attributesFromNetModules.Any()) { wellKnownData = limitedDecodeWellKnownAttributes(attributesFromNetModules, netModuleNames, attributeMatches); } return (CommonAssemblyWellKnownAttributeData)wellKnownData; // Similar to ValidateAttributeUsageAndDecodeWellKnownAttributes, but doesn't load assembly-level attributes from source // and only decodes 3 specific attributes. WellKnownAttributeData limitedDecodeWellKnownAttributes(ImmutableArray<CSharpAttributeData> attributesFromNetModules, ImmutableArray<string> netModuleNames, QuickAttributes attributeMatches) { Debug.Assert(attributesFromNetModules.Any()); Debug.Assert(netModuleNames.Any()); Debug.Assert(attributesFromNetModules.Length == netModuleNames.Length); int netModuleAttributesCount = attributesFromNetModules.Length; HashSet<CSharpAttributeData> uniqueAttributes = null; CommonAssemblyWellKnownAttributeData result = null; // Attributes from the second added module should override attributes from the first added module, etc. // We don't reach here when the attribute was found in source already. for (int i = netModuleAttributesCount - 1; i >= 0; i--) { CSharpAttributeData attribute = attributesFromNetModules[i]; if (!attribute.HasErrors && ValidateAttributeUsageForNetModuleAttribute(attribute, netModuleNames[i], BindingDiagnosticBag.Discarded, ref uniqueAttributes)) { limitedDecodeWellKnownAttribute(attribute, attributeMatches, ref result); } } WellKnownAttributeData.Seal(result); return result; } // Similar to DecodeWellKnownAttribute but only handles 3 specific attributes and ignores diagnostics. void limitedDecodeWellKnownAttribute(CSharpAttributeData attribute, QuickAttributes attributeMatches, ref CommonAssemblyWellKnownAttributeData result) { if (attributeMatches is QuickAttributes.AssemblySignatureKey && attribute.IsTargetAttribute(this, AttributeDescription.AssemblySignatureKeyAttribute)) { result ??= new CommonAssemblyWellKnownAttributeData(); result.AssemblySignatureKeyAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attributeMatches is QuickAttributes.AssemblyKeyFile && attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyFileAttribute)) { result ??= new CommonAssemblyWellKnownAttributeData(); result.AssemblyKeyFileAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attributeMatches is QuickAttributes.AssemblyKeyName && attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyNameAttribute)) { result ??= new CommonAssemblyWellKnownAttributeData(); result.AssemblyKeyContainerAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } } } private CustomAttributesBag<CSharpAttributeData> GetNetModuleAttributesBag() { if (_lazyNetModuleAttributesBag == null) { LoadAndValidateNetModuleAttributes(ref _lazyNetModuleAttributesBag); } return _lazyNetModuleAttributesBag; } internal CommonAssemblyWellKnownAttributeData GetNetModuleDecodedWellKnownAttributeData() { var attributesBag = this.GetNetModuleAttributesBag(); Debug.Assert(attributesBag.IsSealed); return (CommonAssemblyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } internal ImmutableArray<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { var builder = ArrayBuilder<SyntaxList<AttributeListSyntax>>.GetInstance(); var declarations = DeclaringCompilation.MergedRootDeclaration.Declarations; foreach (RootSingleNamespaceDeclaration rootNs in declarations) { if (rootNs.HasAssemblyAttributes) { var tree = rootNs.Location.SourceTree; var root = (CompilationUnitSyntax)tree.GetRoot(); builder.Add(root.AttributeLists); } } return builder.ToImmutableAndFree(); } private void EnsureAttributesAreBound() { if ((_lazySourceAttributesBag == null || !_lazySourceAttributesBag.IsSealed) && LoadAndValidateAttributes(OneOrMany.Create(GetAttributeDeclarations()), ref _lazySourceAttributesBag)) { _state.NotePartComplete(CompletionPart.Attributes); } } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private CustomAttributesBag<CSharpAttributeData> GetSourceAttributesBag() { EnsureAttributesAreBound(); return _lazySourceAttributesBag; } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> /// <remarks> /// NOTE: This method should always be kept as a sealed override. /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetSourceAttributesBag"/> method. /// </remarks> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { var attributes = this.GetSourceAttributesBag().Attributes; var netmoduleAttributes = this.GetNetModuleAttributesBag().Attributes; Debug.Assert(!attributes.IsDefault); Debug.Assert(!netmoduleAttributes.IsDefault); if (attributes.Length > 0) { if (netmoduleAttributes.Length > 0) { attributes = attributes.Concat(netmoduleAttributes); } } else { attributes = netmoduleAttributes; } Debug.Assert(!attributes.IsDefault); return attributes; } /// <summary> /// Returns true if the assembly attribute at the given index is a duplicate assembly attribute that must not be emitted. /// Duplicate assembly attributes are attributes that bind to the same constructor and have identical arguments. /// </summary> /// <remarks> /// This method must be invoked only after all the assembly attributes have been bound. /// </remarks> internal bool IsIndexOfOmittedAssemblyAttribute(int index) { Debug.Assert(_lazyOmittedAttributeIndices == null || !_lazyOmittedAttributeIndices.Any(i => i < 0 || i >= this.GetAttributes().Length)); Debug.Assert(_lazySourceAttributesBag.IsSealed); Debug.Assert(_lazyNetModuleAttributesBag.IsSealed); Debug.Assert(index >= 0); Debug.Assert(index < this.GetAttributes().Length); return _lazyOmittedAttributeIndices != null && _lazyOmittedAttributeIndices.Contains(index); } /// <summary> /// Returns data decoded from source assembly attributes or null if there are none. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// TODO: We should replace methods GetSourceDecodedWellKnownAttributeData and GetNetModuleDecodedWellKnownAttributeData with /// a single method GetDecodedWellKnownAttributeData, which merges DecodedWellKnownAttributeData from source and netmodule attributes. /// </remarks> internal CommonAssemblyWellKnownAttributeData GetSourceDecodedWellKnownAttributeData() { var attributesBag = _lazySourceAttributesBag; if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetSourceAttributesBag(); } return (CommonAssemblyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } #nullable enable /// <remarks> /// This implements the same logic as <see cref="GetSourceDecodedWellKnownAttributeData()"/> /// but loading a smaller set of attributes if possible, to reduce circularity. /// </remarks> private CommonAssemblyWellKnownAttributeData? GetSourceDecodedWellKnownAttributeData(QuickAttributes attribute) { CustomAttributesBag<CSharpAttributeData>? attributesBag = _lazySourceAttributesBag; if (attributesBag?.IsDecodedWellKnownAttributeDataComputed == true) { return (CommonAssemblyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } attributesBag = null; Func<AttributeSyntax, bool> attributeMatches = attribute switch { QuickAttributes.AssemblySignatureKey => isPossibleAssemblySignatureKeyAttribute, QuickAttributes.AssemblyKeyName => isPossibleAssemblyKeyNameAttribute, QuickAttributes.AssemblyKeyFile => isPossibleAssemblyKeyFileAttribute, _ => throw ExceptionUtilities.UnexpectedValue(attribute) }; LoadAndValidateAttributes(OneOrMany.Create(GetAttributeDeclarations()), ref attributesBag, attributeMatchesOpt: attributeMatches); return (CommonAssemblyWellKnownAttributeData?)attributesBag?.DecodedWellKnownAttributeData; bool isPossibleAssemblySignatureKeyAttribute(AttributeSyntax node) { QuickAttributeChecker checker = this.DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder(node).QuickAttributeChecker; return checker.IsPossibleMatch(node, QuickAttributes.AssemblySignatureKey); } bool isPossibleAssemblyKeyNameAttribute(AttributeSyntax node) { QuickAttributeChecker checker = this.DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder(node).QuickAttributeChecker; return checker.IsPossibleMatch(node, QuickAttributes.AssemblyKeyName); } bool isPossibleAssemblyKeyFileAttribute(AttributeSyntax node) { QuickAttributeChecker checker = this.DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder(node).QuickAttributeChecker; return checker.IsPossibleMatch(node, QuickAttributes.AssemblyKeyFile); } } #nullable disable /// <summary> /// This only forces binding of attributes that look like they may be forwarded types attributes (syntactically). /// </summary> internal HashSet<NamedTypeSymbol> GetForwardedTypes() { CustomAttributesBag<CSharpAttributeData> attributesBag = _lazySourceAttributesBag; if (attributesBag?.IsDecodedWellKnownAttributeDataComputed == true) { // Use already decoded attributes return ((CommonAssemblyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData)?.ForwardedTypes; } attributesBag = null; LoadAndValidateAttributes(OneOrMany.Create(GetAttributeDeclarations()), ref attributesBag, attributeMatchesOpt: this.IsPossibleForwardedTypesAttribute); var wellKnownAttributeData = (CommonAssemblyWellKnownAttributeData)attributesBag?.DecodedWellKnownAttributeData; return wellKnownAttributeData?.ForwardedTypes; } private bool IsPossibleForwardedTypesAttribute(AttributeSyntax node) { QuickAttributeChecker checker = this.DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder(node).QuickAttributeChecker; return checker.IsPossibleMatch(node, QuickAttributes.TypeForwardedTo); } private static IEnumerable<Cci.SecurityAttribute> GetSecurityAttributes(CustomAttributesBag<CSharpAttributeData> attributesBag) { Debug.Assert(attributesBag.IsSealed); var wellKnownAttributeData = (CommonAssemblyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; if (wellKnownAttributeData != null) { SecurityWellKnownAttributeData securityData = wellKnownAttributeData.SecurityInformation; if (securityData != null) { foreach (var securityAttribute in securityData.GetSecurityAttributes<CSharpAttributeData>(attributesBag.Attributes)) { yield return securityAttribute; } } } } internal IEnumerable<Cci.SecurityAttribute> GetSecurityAttributes() { // user defined security attributes: foreach (var securityAttribute in GetSecurityAttributes(this.GetSourceAttributesBag())) { yield return securityAttribute; } // Net module assembly security attributes: foreach (var securityAttribute in GetSecurityAttributes(this.GetNetModuleAttributesBag())) { yield return securityAttribute; } // synthesized security attributes: if (_compilation.Options.AllowUnsafe) { // NOTE: GlobalAttrBind::EmitCompilerGeneratedAttrs skips attribute if the well-known types aren't available. if (!(_compilation.GetWellKnownType(WellKnownType.System_Security_UnverifiableCodeAttribute) is MissingMetadataTypeSymbol) && !(_compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityPermissionAttribute) is MissingMetadataTypeSymbol)) { var securityActionType = _compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction); if (!(securityActionType is MissingMetadataTypeSymbol)) { var fieldRequestMinimum = (FieldSymbol)_compilation.GetWellKnownTypeMember(WellKnownMember.System_Security_Permissions_SecurityAction__RequestMinimum); // NOTE: Dev10 handles missing enum value. object constantValue = (object)fieldRequestMinimum == null || fieldRequestMinimum.HasUseSiteError ? 0 : fieldRequestMinimum.ConstantValue; var typedConstantRequestMinimum = new TypedConstant(securityActionType, TypedConstantKind.Enum, constantValue); var boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); Debug.Assert(!boolType.HasUseSiteError, "Use site errors should have been checked ahead of time (type bool)."); var typedConstantTrue = new TypedConstant(boolType, TypedConstantKind.Primitive, value: true); var attribute = _compilation.TrySynthesizeAttribute( WellKnownMember.System_Security_Permissions_SecurityPermissionAttribute__ctor, ImmutableArray.Create(typedConstantRequestMinimum), ImmutableArray.Create(new KeyValuePair<WellKnownMember, TypedConstant>( WellKnownMember.System_Security_Permissions_SecurityPermissionAttribute__SkipVerification, typedConstantTrue))); if (attribute != null) { yield return new Cci.SecurityAttribute((DeclarativeSecurityAction)(int)constantValue, attribute); } } } } } internal override ImmutableArray<AssemblySymbol> GetNoPiaResolutionAssemblies() { return _modules[0].GetReferencedAssemblySymbols(); } internal override void SetNoPiaResolutionAssemblies(ImmutableArray<AssemblySymbol> assemblies) { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<AssemblySymbol> GetLinkedReferencedAssemblies() { // SourceAssemblySymbol is never used directly as a reference // when it is or any of its references is linked. return default(ImmutableArray<AssemblySymbol>); } internal override void SetLinkedReferencedAssemblies(ImmutableArray<AssemblySymbol> assemblies) { // SourceAssemblySymbol is never used directly as a reference // when it is or any of its references is linked. throw ExceptionUtilities.Unreachable; } internal override bool IsLinked { get { return false; } } internal bool DeclaresTheObjectClass { get { if ((object)this.CorLibrary != (object)this) { return false; } var obj = GetSpecialType(SpecialType.System_Object); return !obj.IsErrorType() && obj.DeclaredAccessibility == Accessibility.Public; } } public override bool MightContainExtensionMethods { get { // Note this method returns true until all ContainsExtensionMethods is // called, after which the correct value will be returned. In other words, // the return value may change from true to false on subsequent calls. if (_lazyContainsExtensionMethods.HasValue()) { return _lazyContainsExtensionMethods.Value(); } return true; } } private bool HasDebuggableAttribute { get { CommonAssemblyWellKnownAttributeData assemblyData = this.GetSourceDecodedWellKnownAttributeData(); return assemblyData != null && assemblyData.HasDebuggableAttribute; } } private bool HasReferenceAssemblyAttribute { get { CommonAssemblyWellKnownAttributeData assemblyData = this.GetSourceDecodedWellKnownAttributeData(); return assemblyData != null && assemblyData.HasReferenceAssemblyAttribute; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); CSharpCompilationOptions options = _compilation.Options; bool isBuildingNetModule = options.OutputKind.IsNetModule(); bool containsExtensionMethods = this.ContainsExtensionMethods(); if (containsExtensionMethods) { // No need to check if [Extension] attribute was explicitly set since // we'll issue CS1112 error in those cases and won't generate IL. AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor)); } // Synthesize CompilationRelaxationsAttribute only if all the following requirements are met: // (a) We are not building a netmodule. // (b) There is no applied CompilationRelaxationsAttribute assembly attribute in source. // (c) There is no applied CompilationRelaxationsAttribute assembly attribute for any of the added PE modules. // Above requirements also hold for synthesizing RuntimeCompatibilityAttribute attribute. bool emitCompilationRelaxationsAttribute = !isBuildingNetModule && !this.Modules.Any(m => m.HasAssemblyCompilationRelaxationsAttribute); if (emitCompilationRelaxationsAttribute) { // Synthesize attribute: [CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] // NOTE: GlobalAttrBind::EmitCompilerGeneratedAttrs skips attribute if the well-known types aren't available. if (!(_compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute) is MissingMetadataTypeSymbol)) { var int32Type = _compilation.GetSpecialType(SpecialType.System_Int32); Debug.Assert(!int32Type.HasUseSiteError, "Use site errors should have been checked ahead of time (type int)."); var typedConstantNoStringInterning = new TypedConstant(int32Type, TypedConstantKind.Primitive, Cci.Constants.CompilationRelaxations_NoStringInterning); AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32, ImmutableArray.Create(typedConstantNoStringInterning))); } } bool emitRuntimeCompatibilityAttribute = !isBuildingNetModule && !this.Modules.Any(m => m.HasAssemblyRuntimeCompatibilityAttribute); if (emitRuntimeCompatibilityAttribute) { // Synthesize attribute: [RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] // NOTE: GlobalAttrBind::EmitCompilerGeneratedAttrs skips attribute if the well-known types aren't available. if (!(_compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute) is MissingMetadataTypeSymbol)) { var boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); Debug.Assert(!boolType.HasUseSiteError, "Use site errors should have been checked ahead of time (type bool)."); var typedConstantTrue = new TypedConstant(boolType, TypedConstantKind.Primitive, value: true); AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor, ImmutableArray<TypedConstant>.Empty, ImmutableArray.Create(new KeyValuePair<WellKnownMember, TypedConstant>( WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows, typedConstantTrue)))); } } // Synthesize DebuggableAttribute only if all the following requirements are met: // (a) We are not building a netmodule. // (b) We are emitting debug information (full or pdbonly). // (c) There is no applied DebuggableAttribute assembly attribute in source. // CONSIDER: Native VB compiler and Roslyn VB compiler also have an additional requirement: There is no applied DebuggableAttribute *module* attribute in source. // CONSIDER: Should we check for module DebuggableAttribute? if (!isBuildingNetModule && !this.HasDebuggableAttribute) { AddSynthesizedAttribute(ref attributes, _compilation.SynthesizeDebuggableAttribute()); } if (_compilation.Options.OutputKind == OutputKind.NetModule) { // If the attribute is applied in source, do not add synthetic one. // If its value is different from the supplied through options, an error should have been reported by now. if (!string.IsNullOrEmpty(_compilation.Options.CryptoKeyContainer) && (object)AssemblyKeyContainerAttributeSetting == (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { var stringType = _compilation.GetSpecialType(SpecialType.System_String); Debug.Assert(!stringType.HasUseSiteError, "Use site errors should have been checked ahead of time (type string)."); var typedConstant = new TypedConstant(stringType, TypedConstantKind.Primitive, _compilation.Options.CryptoKeyContainer); AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute(WellKnownMember.System_Reflection_AssemblyKeyNameAttribute__ctor, ImmutableArray.Create(typedConstant))); } if (!String.IsNullOrEmpty(_compilation.Options.CryptoKeyFile) && (object)AssemblyKeyFileAttributeSetting == (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { var stringType = _compilation.GetSpecialType(SpecialType.System_String); Debug.Assert(!stringType.HasUseSiteError, "Use site errors should have been checked ahead of time (type string)."); var typedConstant = new TypedConstant(stringType, TypedConstantKind.Primitive, _compilation.Options.CryptoKeyFile); AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute(WellKnownMember.System_Reflection_AssemblyKeyFileAttribute__ctor, ImmutableArray.Create(typedConstant))); } } } /// <summary> /// Returns true if and only if at least one type within the assembly contains /// extension methods. Note, this method is expensive since it potentially /// inspects all types within the assembly. The expectation is that this method is /// only called at emit time, when all types have been or will be traversed anyway. /// </summary> private bool ContainsExtensionMethods() { if (!_lazyContainsExtensionMethods.HasValue()) { _lazyContainsExtensionMethods = ContainsExtensionMethods(_modules).ToThreeState(); } return _lazyContainsExtensionMethods.Value(); } private static bool ContainsExtensionMethods(ImmutableArray<ModuleSymbol> modules) { foreach (var module in modules) { if (ContainsExtensionMethods(module.GlobalNamespace)) { return true; } } return false; } private static bool ContainsExtensionMethods(NamespaceSymbol ns) { foreach (var member in ns.GetMembersUnordered()) { switch (member.Kind) { case SymbolKind.Namespace: if (ContainsExtensionMethods((NamespaceSymbol)member)) { return true; } break; case SymbolKind.NamedType: if (((NamedTypeSymbol)member).MightContainExtensionMethods) { return true; } break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } return false; } //Once the computation of the AssemblyIdentity is complete, check whether //any of the IVT access grants that were optimistically made during AssemblyIdentity computation //are in fact invalid now that the full identity is known. private void CheckOptimisticIVTAccessGrants(BindingDiagnosticBag bag) { ConcurrentDictionary<AssemblySymbol, bool> haveGrantedAssemblies = _optimisticallyGrantedInternalsAccess; if (haveGrantedAssemblies != null) { foreach (var otherAssembly in haveGrantedAssemblies.Keys) { IVTConclusion conclusion = MakeFinalIVTDetermination(otherAssembly); Debug.Assert(conclusion != IVTConclusion.NoRelationshipClaimed); if (conclusion == IVTConclusion.PublicKeyDoesntMatch) bag.Add(ErrorCode.ERR_FriendRefNotEqualToThis, NoLocation.Singleton, otherAssembly.Identity, this.Identity); else if (conclusion == IVTConclusion.OneSignedOneNot) bag.Add(ErrorCode.ERR_FriendRefSigningMismatch, NoLocation.Singleton, otherAssembly.Identity); } } } internal override IEnumerable<ImmutableArray<byte>> GetInternalsVisibleToPublicKeys(string simpleName) { //EDMAURER assume that if EnsureAttributesAreBound() returns, then the internals visible to map has been populated. //Do not optimize by checking if m_lazyInternalsVisibleToMap is Nothing. It may be non-null yet still //incomplete because another thread is in the process of building it. EnsureAttributesAreBound(); if (_lazyInternalsVisibleToMap == null) return SpecializedCollections.EmptyEnumerable<ImmutableArray<byte>>(); ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, string>> result = null; _lazyInternalsVisibleToMap.TryGetValue(simpleName, out result); return (result != null) ? result.Keys : SpecializedCollections.EmptyEnumerable<ImmutableArray<byte>>(); } internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol potentialGiverOfAccess) { // Ensure that optimistic IVT access is only granted to requests that originated on the thread //that is trying to compute the assembly identity. This gives us deterministic behavior when //two threads are checking IVT access but only one of them is in the process of computing identity. //as an optimization confirm that the identity has not yet been computed to avoid testing TLS if (_lazyStrongNameKeys == null) { var assemblyWhoseKeysAreBeingComputed = t_assemblyForWhichCurrentThreadIsComputingKeys; if ((object)assemblyWhoseKeysAreBeingComputed != null) { //ThrowIfFalse(assemblyWhoseKeysAreBeingComputed Is Me); if (!potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(this.Name).IsEmpty()) { if (_optimisticallyGrantedInternalsAccess == null) Interlocked.CompareExchange(ref _optimisticallyGrantedInternalsAccess, new ConcurrentDictionary<AssemblySymbol, bool>(), null); _optimisticallyGrantedInternalsAccess.TryAdd(potentialGiverOfAccess, true); return true; } else return false; } } IVTConclusion conclusion = MakeFinalIVTDetermination(potentialGiverOfAccess); return conclusion == IVTConclusion.Match || conclusion == IVTConclusion.OneSignedOneNot; } private AssemblyIdentity ComputeIdentity() { return new AssemblyIdentity( _assemblySimpleName, VersionHelper.GenerateVersionFromPatternAndCurrentTime(_compilation.Options.CurrentLocalTime, AssemblyVersionAttributeSetting), this.AssemblyCultureAttributeSetting, StrongNameKeys.PublicKey, hasPublicKey: !StrongNameKeys.PublicKey.IsDefault); } //This maps from assembly name to a set of public keys. It uses concurrent dictionaries because it is built, //one attribute at a time, in the callback that validates an attribute's application to a symbol. It is assumed //to be complete after a call to GetAttributes(). The second dictionary is acting like a set. The value element is //only used when the key is empty in which case it stores the location and value of the attribute string which //may be used to construct a diagnostic if the assembly being compiled is found to be strong named. private ConcurrentDictionary<string, ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, string>>> _lazyInternalsVisibleToMap; private static Location GetAssemblyAttributeLocationForDiagnostic(AttributeSyntax attributeSyntaxOpt) { return (object)attributeSyntaxOpt != null ? attributeSyntaxOpt.Location : NoLocation.Singleton; } private void DecodeTypeForwardedToAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { // this code won't be called unless we bound a well-formed, semantically correct ctor call. Debug.Assert(!arguments.Attribute.HasErrors); var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; TypeSymbol forwardedType = (TypeSymbol)arguments.Attribute.CommonConstructorArguments[0].ValueInternal; // This can happen if the argument is the null literal. if ((object)forwardedType == null) { diagnostics.Add(ErrorCode.ERR_InvalidFwdType, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt)); return; } UseSiteInfo<AssemblySymbol> useSiteInfo = forwardedType.GetUseSiteInfo(); if (useSiteInfo.DiagnosticInfo?.Code != (int)ErrorCode.ERR_UnexpectedUnboundGenericName && diagnostics.Add(useSiteInfo, useSiteInfo.DiagnosticInfo is object ? GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt) : Location.None)) { return; } Debug.Assert(forwardedType.TypeKind != TypeKind.Error); if (forwardedType.ContainingAssembly == this) { diagnostics.Add(ErrorCode.ERR_ForwardedTypeInThisAssembly, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt), forwardedType); return; } if ((object)forwardedType.ContainingType != null) { diagnostics.Add(ErrorCode.ERR_ForwardedTypeIsNested, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt), forwardedType, forwardedType.ContainingType); return; } if (forwardedType.Kind != SymbolKind.NamedType) { // NOTE: Dev10 actually tests whether the forwarded type is an aggregate. This would seem to // exclude nullable and void, but that shouldn't be an issue because they have to be defined in // corlib (since they are special types) and corlib can't refer to other assemblies (by definition). diagnostics.Add(ErrorCode.ERR_InvalidFwdType, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt)); return; } // NOTE: There is no danger of the type being forwarded back to this assembly, because the type // won't even bind successfully unless we have a reference to an assembly that actually contains // the type. var assemblyData = arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>(); HashSet<NamedTypeSymbol> forwardedTypes = assemblyData.ForwardedTypes; if (forwardedTypes == null) { forwardedTypes = new HashSet<NamedTypeSymbol>() { (NamedTypeSymbol)forwardedType }; assemblyData.ForwardedTypes = forwardedTypes; } else if (!forwardedTypes.Add((NamedTypeSymbol)forwardedType)) { // NOTE: For the purposes of reporting this error, Dev10 considers C<int> and C<char> // different types. However, it will actually emit a single forwarder for C`1 (i.e. // we'll have to de-dup again at emit time). diagnostics.Add(ErrorCode.ERR_DuplicateTypeForwarder, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt), forwardedType); } } private void DecodeOneInternalsVisibleToAttribute( AttributeSyntax nodeOpt, CSharpAttributeData attrData, BindingDiagnosticBag diagnostics, int index, ref ConcurrentDictionary<string, ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, string>>> lazyInternalsVisibleToMap) { // this code won't be called unless we bound a well-formed, semantically correct ctor call. Debug.Assert(!attrData.HasErrors); string displayName = (string)attrData.CommonConstructorArguments[0].ValueInternal; if (displayName == null) { diagnostics.Add(ErrorCode.ERR_CannotPassNullForFriendAssembly, GetAssemblyAttributeLocationForDiagnostic(nodeOpt)); return; } AssemblyIdentity identity; AssemblyIdentityParts parts; if (!AssemblyIdentity.TryParseDisplayName(displayName, out identity, out parts)) { diagnostics.Add(ErrorCode.WRN_InvalidAssemblyName, GetAssemblyAttributeLocationForDiagnostic(nodeOpt), displayName); AddOmittedAttributeIndex(index); return; } // Allow public key token due to compatibility reasons, but we are not going to use its value. const AssemblyIdentityParts allowedParts = AssemblyIdentityParts.Name | AssemblyIdentityParts.PublicKey | AssemblyIdentityParts.PublicKeyToken; if ((parts & ~allowedParts) != 0) { diagnostics.Add(ErrorCode.ERR_FriendAssemblyBadArgs, GetAssemblyAttributeLocationForDiagnostic(nodeOpt), displayName); return; } if (lazyInternalsVisibleToMap == null) { Interlocked.CompareExchange(ref lazyInternalsVisibleToMap, new ConcurrentDictionary<string, ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, String>>>(StringComparer.OrdinalIgnoreCase), null); } //later, once the identity is established we confirm that if the assembly being //compiled is signed all of the IVT attributes specify a key. Stash the location for that //in the event that a diagnostic needs to be produced. Tuple<Location, string> locationAndValue = null; // only need to store anything when there is no public key. The only reason to store // this stuff is for production of errors when the assembly is signed but the IVT attrib // doesn't contain a public key. if (identity.PublicKey.IsEmpty) { locationAndValue = new Tuple<Location, string>(GetAssemblyAttributeLocationForDiagnostic(nodeOpt), displayName); } //when two threads are attempting to update the internalsVisibleToMap one of these TryAdd() //calls can fail. We assume that the 'other' thread in that case will successfully add the same //contents eventually. ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, string>> keys = null; if (lazyInternalsVisibleToMap.TryGetValue(identity.Name, out keys)) { keys.TryAdd(identity.PublicKey, locationAndValue); } else { keys = new ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, String>>(); keys.TryAdd(identity.PublicKey, locationAndValue); lazyInternalsVisibleToMap.TryAdd(identity.Name, keys); } } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return this; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.Assembly; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { return IsInteractive ? AttributeLocation.None : AttributeLocation.Assembly | AttributeLocation.Module; } } internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { DecodeWellKnownAttribute(ref arguments, arguments.Index, isFromNetModule: false); } private void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, int index, bool isFromNetModule) { var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); int signature; var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; if (attribute.IsTargetAttribute(this, AttributeDescription.InternalsVisibleToAttribute)) { DecodeOneInternalsVisibleToAttribute(arguments.AttributeSyntaxOpt, attribute, diagnostics, index, ref _lazyInternalsVisibleToMap); } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblySignatureKeyAttribute)) { var signatureKey = (string)attribute.CommonConstructorArguments[0].ValueInternal; arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblySignatureKeyAttributeSetting = signatureKey; if (!StrongNameKeys.IsValidPublicKeyString(signatureKey)) { diagnostics.Add(ErrorCode.ERR_InvalidSignaturePublicKey, attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt)); } } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyFileAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyKeyFileAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyNameAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyKeyContainerAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDelaySignAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyDelaySignAttributeSetting = (bool)attribute.CommonConstructorArguments[0].ValueInternal ? ThreeState.True : ThreeState.False; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyVersionAttribute)) { string verString = (string)attribute.CommonConstructorArguments[0].ValueInternal; Version version; if (!VersionHelper.TryParseAssemblyVersion(verString, allowWildcard: !_compilation.IsEmitDeterministic, version: out version)) { Location attributeArgumentSyntaxLocation = attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt); bool foundBadWildcard = _compilation.IsEmitDeterministic && verString?.Contains('*') == true; diagnostics.Add(foundBadWildcard ? ErrorCode.ERR_InvalidVersionFormatDeterministic : ErrorCode.ERR_InvalidVersionFormat, attributeArgumentSyntaxLocation); } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyVersionAttributeSetting = version; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyFileVersionAttribute)) { Version dummy; string verString = (string)attribute.CommonConstructorArguments[0].ValueInternal; if (!VersionHelper.TryParse(verString, version: out dummy)) { Location attributeArgumentSyntaxLocation = attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt); diagnostics.Add(ErrorCode.WRN_InvalidVersionFormat, attributeArgumentSyntaxLocation); } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyFileVersionAttributeSetting = verString; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTitleAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyTitleAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDescriptionAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyDescriptionAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCultureAttribute)) { var cultureString = (string)attribute.CommonConstructorArguments[0].ValueInternal; if (!string.IsNullOrEmpty(cultureString)) { if (_compilation.Options.OutputKind.IsApplication()) { diagnostics.Add(ErrorCode.ERR_InvalidAssemblyCultureForExe, attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt)); } else if (!AssemblyIdentity.IsValidCultureName(cultureString)) { diagnostics.Add(ErrorCode.ERR_InvalidAssemblyCulture, attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt)); cultureString = null; } } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyCultureAttributeSetting = cultureString; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCompanyAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyCompanyAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyProductAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyProductAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyInformationalVersionAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyInformationalVersionAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.SatelliteContractVersionAttribute)) { //just check the format of this one, don't do anything else with it. Version dummy; string verString = (string)attribute.CommonConstructorArguments[0].ValueInternal; if (!VersionHelper.TryParseAssemblyVersion(verString, allowWildcard: false, version: out dummy)) { Location attributeArgumentSyntaxLocation = attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt); diagnostics.Add(ErrorCode.ERR_InvalidVersionFormat2, attributeArgumentSyntaxLocation); } } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCopyrightAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyCopyrightAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTrademarkAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyTrademarkAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if ((signature = attribute.GetTargetAttributeSignatureIndex(this, AttributeDescription.AssemblyFlagsAttribute)) != -1) { object value = attribute.CommonConstructorArguments[0].ValueInternal; AssemblyFlags nameFlags; if (signature == 0 || signature == 1) { nameFlags = (AssemblyFlags)(AssemblyNameFlags)value; } else { nameFlags = (AssemblyFlags)(uint)value; } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyFlagsAttributeSetting = nameFlags; } else if (attribute.IsSecurityAttribute(_compilation)) { attribute.DecodeSecurityAttribute<CommonAssemblyWellKnownAttributeData>(this, _compilation, ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.ClassInterfaceAttribute)) { attribute.DecodeClassInterfaceAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.TypeLibVersionAttribute)) { ValidateIntegralAttributeNonNegativeArguments(attribute, arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.ComCompatibleVersionAttribute)) { ValidateIntegralAttributeNonNegativeArguments(attribute, arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.GuidAttribute)) { attribute.DecodeGuidAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.CompilationRelaxationsAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().HasCompilationRelaxationsAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.ReferenceAssemblyAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().HasReferenceAssemblyAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.RuntimeCompatibilityAttribute)) { bool wrapNonExceptionThrows = true; foreach (var namedArg in attribute.CommonNamedArguments) { switch (namedArg.Key) { case "WrapNonExceptionThrows": wrapNonExceptionThrows = namedArg.Value.DecodeValue<bool>(SpecialType.System_Boolean); break; } } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().RuntimeCompatibilityWrapNonExceptionThrows = wrapNonExceptionThrows; } else if (attribute.IsTargetAttribute(this, AttributeDescription.DebuggableAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().HasDebuggableAttribute = true; } else if (!isFromNetModule && attribute.IsTargetAttribute(this, AttributeDescription.TypeForwardedToAttribute)) { DecodeTypeForwardedToAttribute(ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.CaseSensitiveExtensionAttribute)) { if ((object)arguments.AttributeSyntaxOpt != null) { // [Extension] attribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitExtension, arguments.AttributeSyntaxOpt.Location); } } else if ((signature = attribute.GetTargetAttributeSignatureIndex(this, AttributeDescription.AssemblyAlgorithmIdAttribute)) != -1) { object value = attribute.CommonConstructorArguments[0].ValueInternal; AssemblyHashAlgorithm algorithmId; if (signature == 0) { algorithmId = (AssemblyHashAlgorithm)value; } else { algorithmId = (AssemblyHashAlgorithm)(uint)value; } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyAlgorithmIdAttributeSetting = algorithmId; } } // Checks that the integral arguments for the given well-known attribute are non-negative. private static void ValidateIntegralAttributeNonNegativeArguments(CSharpAttributeData attribute, AttributeSyntax nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!attribute.HasErrors); int argCount = attribute.CommonConstructorArguments.Length; for (int i = 0; i < argCount; i++) { int arg = attribute.GetConstructorArgument<int>(i, SpecialType.System_Int32); if (arg < 0) { // CS0591: Invalid value for argument to '{0}' attribute Location attributeArgumentSyntaxLocation = attribute.GetAttributeArgumentSyntaxLocation(i, nodeOpt); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, (object)nodeOpt != null ? nodeOpt.GetErrorDisplayName() : ""); } } } internal void NoteFieldAccess(FieldSymbol field, bool read, bool write) { var container = field.ContainingType as SourceMemberContainerTypeSymbol; if ((object)container == null) { // field is not in source. return; } container.EnsureFieldDefinitionsNoted(); if (_unusedFieldWarnings.IsDefault) { if (read) { _unreadFields.Remove(field); } if (write) { bool _; _unassignedFieldsMap.TryRemove(field, out _); } } else { // It's acceptable to run flow analysis again after the diagnostics have been computed - just // make sure that the nothing is different than the first time. Debug.Assert( !(read && _unreadFields.Remove(field)), "we are already reporting unused field warnings, there could be no more changes"); Debug.Assert( !(write && _unassignedFieldsMap.ContainsKey(field)), "we are already reporting unused field warnings, there could be no more changes"); } } internal void NoteFieldDefinition(FieldSymbol field, bool isInternal, bool isUnread) { Debug.Assert(_unusedFieldWarnings.IsDefault, "We shouldn't have computed the diagnostics if we're still noting definitions."); _unassignedFieldsMap.TryAdd(field, isInternal); if (isUnread) { _unreadFields.Add(field); } } internal override bool IsNetModule() => this._compilation.Options.OutputKind.IsNetModule(); /// <summary> /// Get the warnings for unused fields. This should only be fetched when all method bodies have been compiled. /// </summary> internal ImmutableArray<Diagnostic> GetUnusedFieldWarnings(CancellationToken cancellationToken) { if (_unusedFieldWarnings.IsDefault) { //Our maps of unread and unassigned fields won't be done until the assembly is complete. this.ForceComplete(locationOpt: null, cancellationToken: cancellationToken); Debug.Assert(this.HasComplete(CompletionPart.Module), "Don't consume unused field information if there are still types to be processed."); // Build this up in a local before we assign it to this.unusedFieldWarnings (so other threads // can see that it's not done). DiagnosticBag diagnostics = DiagnosticBag.GetInstance(); // NOTE: two threads can come in here at the same time. If they do, then they will // share the diagnostic bag. That's alright, as long as each one processes only // the fields that it successfully removes from the shared map/set. Furthermore, // there should be no problem with re-calling this method on the same assembly, // since there will be nothing left in the map/set the second time. bool internalsAreVisible = this.InternalsAreVisible || this.IsNetModule(); HashSet<FieldSymbol> handledUnreadFields = null; foreach (FieldSymbol field in _unassignedFieldsMap.Keys) // Not mutating, so no snapshot required. { bool isInternalAccessibility; bool success = _unassignedFieldsMap.TryGetValue(field, out isInternalAccessibility); Debug.Assert(success, "Once CompletionPart.Module is set, no-one should be modifying the map."); if (isInternalAccessibility && internalsAreVisible) { continue; } if (!field.CanBeReferencedByName) { continue; } var containingType = field.ContainingType as SourceNamedTypeSymbol; if ((object)containingType == null) { continue; } if (field is TupleErrorFieldSymbol) { continue; } bool unread = _unreadFields.Contains(field); if (unread) { if (handledUnreadFields == null) { handledUnreadFields = new HashSet<FieldSymbol>(); } handledUnreadFields.Add(field); } if (containingType.HasStructLayoutAttribute) { continue; } Symbol associatedPropertyOrEvent = field.AssociatedSymbol; if ((object)associatedPropertyOrEvent != null && associatedPropertyOrEvent.Kind == SymbolKind.Event) { if (unread) { diagnostics.Add(ErrorCode.WRN_UnreferencedEvent, associatedPropertyOrEvent.Locations.FirstOrNone(), associatedPropertyOrEvent); } } else if (unread) { diagnostics.Add(ErrorCode.WRN_UnreferencedField, field.Locations.FirstOrNone(), field); } else { diagnostics.Add(ErrorCode.WRN_UnassignedInternalField, field.Locations.FirstOrNone(), field, DefaultValue(field.Type)); } } foreach (FieldSymbol field in _unreadFields) // Not mutating, so no snapshot required. { if (handledUnreadFields != null && handledUnreadFields.Contains(field)) { // Handled in the first foreach loop. continue; } if (!field.CanBeReferencedByName) { continue; } var containingType = field.ContainingType as SourceNamedTypeSymbol; if ((object)containingType != null && !containingType.HasStructLayoutAttribute) { diagnostics.Add(ErrorCode.WRN_UnreferencedFieldAssg, field.Locations.FirstOrNone(), field); } } ImmutableInterlocked.InterlockedInitialize(ref _unusedFieldWarnings, diagnostics.ToReadOnlyAndFree()); } Debug.Assert(!_unusedFieldWarnings.IsDefault); return _unusedFieldWarnings; } private static string DefaultValue(TypeSymbol type) { // TODO: localize these strings if (type.IsReferenceType) return "null"; switch (type.SpecialType) { case SpecialType.System_Boolean: return "false"; case SpecialType.System_Byte: case SpecialType.System_Decimal: case SpecialType.System_Double: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_SByte: case SpecialType.System_Single: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: return "0"; default: return ""; } } internal override NamedTypeSymbol TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies) { int forcedArity = emittedName.ForcedArity; if (emittedName.UseCLSCompliantNameArityEncoding) { if (forcedArity == -1) { forcedArity = emittedName.InferredArity; } else if (forcedArity != emittedName.InferredArity) { return null; } Debug.Assert(forcedArity == emittedName.InferredArity); } if (_lazyForwardedTypesFromSource == null) { IDictionary<string, NamedTypeSymbol> forwardedTypesFromSource; // Get the TypeForwardedTo attributes with minimal binding to avoid cycle problems HashSet<NamedTypeSymbol> forwardedTypes = GetForwardedTypes(); if (forwardedTypes != null) { forwardedTypesFromSource = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance); foreach (NamedTypeSymbol forwardedType in forwardedTypes) { NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition; Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?"); string fullEmittedName = MetadataHelpers.BuildQualifiedName(originalDefinition.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), originalDefinition.MetadataName); // Since we need to allow multiple constructions of the same generic type at the source // level, we need to de-dup the original definitions. forwardedTypesFromSource[fullEmittedName] = originalDefinition; } } else { forwardedTypesFromSource = SpecializedCollections.EmptyDictionary<string, NamedTypeSymbol>(); } _lazyForwardedTypesFromSource = forwardedTypesFromSource; } NamedTypeSymbol result; if (_lazyForwardedTypesFromSource.TryGetValue(emittedName.FullName, out result)) { if ((forcedArity == -1 || result.Arity == forcedArity) && (!emittedName.UseCLSCompliantNameArityEncoding || result.Arity == 0 || result.MangleName)) { return result; } } else if (!_compilation.Options.OutputKind.IsNetModule()) { // See if any of added modules forward the type. // Similar to attributes, type forwarders from the second added module should override type forwarders from the first added module, etc. for (int i = _modules.Length - 1; i > 0; i--) { var peModuleSymbol = (Metadata.PE.PEModuleSymbol)_modules[i]; (AssemblySymbol firstSymbol, AssemblySymbol secondSymbol) = peModuleSymbol.GetAssembliesForForwardedType(ref emittedName); if ((object)firstSymbol != null) { if ((object)secondSymbol != null) { return CreateMultipleForwardingErrorTypeSymbol(ref emittedName, peModuleSymbol, firstSymbol, secondSymbol); } // Don't bother to check the forwarded-to assembly if we've already seen it. if (visitedAssemblies != null && visitedAssemblies.Contains(firstSymbol)) { return CreateCycleInTypeForwarderErrorTypeSymbol(ref emittedName); } else { visitedAssemblies = new ConsList<AssemblySymbol>(this, visitedAssemblies ?? ConsList<AssemblySymbol>.Empty); return firstSymbol.LookupTopLevelMetadataTypeWithCycleDetection(ref emittedName, visitedAssemblies, digThroughForwardedTypes: true); } } } } return null; } internal override IEnumerable<NamedTypeSymbol> GetAllTopLevelForwardedTypes() { return PEModuleBuilder.GetForwardedTypes(this, builder: null); } public override AssemblyMetadata GetMetadata() => null; protected override ISymbol CreateISymbol() { return new PublicModel.SourceAssemblySymbol(this); } } }
// Licensed to the .NET Foundation under one or more 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.Reflection; using System.Security.Cryptography; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; using CommonAssemblyWellKnownAttributeData = Microsoft.CodeAnalysis.CommonAssemblyWellKnownAttributeData<Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol>; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an assembly built by compiler. /// </summary> internal sealed partial class SourceAssemblySymbol : MetadataOrSourceAssemblySymbol, ISourceAssemblySymbolInternal, IAttributeTargetSymbol { /// <summary> /// A Compilation the assembly is created for. /// </summary> private readonly CSharpCompilation _compilation; private SymbolCompletionState _state; /// <summary> /// Assembly's identity. /// </summary> internal AssemblyIdentity lazyAssemblyIdentity; private readonly string _assemblySimpleName; // Computing the identity requires computing the public key. Computing the public key // can require binding attributes that contain version or strong name information. // Attribute binding will check type visibility which will possibly // check IVT relationships. To correctly determine the IVT relationship requires the public key. // To avoid infinite recursion, this type notes, per thread, the assembly for which the thread // is actively computing the public key (assemblyForWhichCurrentThreadIsComputingKeys). Should a request to determine IVT // relationship occur on the thread that is computing the public key, access is optimistically // granted provided the simple assembly names match. When such access is granted // the assembly to which we have been granted access is noted (optimisticallyGrantedInternalsAccess). // After the public key has been computed, the set of optimistic grants is reexamined // to ensure that full identities match. This may produce diagnostics. private StrongNameKeys _lazyStrongNameKeys; /// <summary> /// A list of modules the assembly consists of. /// The first (index=0) module is a SourceModuleSymbol, which is a primary module, the rest are net-modules. /// </summary> private readonly ImmutableArray<ModuleSymbol> _modules; /// <summary> /// Bag of assembly's custom attributes and decoded well-known attribute data from source. /// </summary> private CustomAttributesBag<CSharpAttributeData> _lazySourceAttributesBag; /// <summary> /// Bag of assembly's custom attributes and decoded well-known attribute data from added netmodules. /// </summary> private CustomAttributesBag<CSharpAttributeData> _lazyNetModuleAttributesBag; private IDictionary<string, NamedTypeSymbol> _lazyForwardedTypesFromSource; /// <summary> /// Indices of attributes that will not be emitted for one of two reasons: /// - They are duplicates of another attribute (i.e. attributes that bind to the same constructor and have identical arguments) /// - They are InternalsVisibleToAttributes with invalid assembly identities /// </summary> /// <remarks> /// These indices correspond to the merged assembly attributes from source and added net modules, i.e. attributes returned by <see cref="GetAttributes"/> method. /// </remarks> private ConcurrentSet<int> _lazyOmittedAttributeIndices; private ThreeState _lazyContainsExtensionMethods; /// <summary> /// Map for storing effectively private or effectively internal fields declared in this assembly but never initialized nor assigned. /// Each {symbol, bool} key-value pair in this map indicates the following: /// (a) Key: Unassigned field symbol. /// (b) Value: True if the unassigned field is effectively internal, false otherwise. /// </summary> private readonly ConcurrentDictionary<FieldSymbol, bool> _unassignedFieldsMap = new ConcurrentDictionary<FieldSymbol, bool>(); /// <summary> /// private fields declared in this assembly but never read /// </summary> private readonly ConcurrentSet<FieldSymbol> _unreadFields = new ConcurrentSet<FieldSymbol>(); /// <summary> /// We imitate the native compiler's policy of not warning about unused fields /// when the enclosing type is used by an extern method for a ref argument. /// Here we keep track of those types. /// </summary> internal ConcurrentSet<TypeSymbol> TypesReferencedInExternalMethods = new ConcurrentSet<TypeSymbol>(); /// <summary> /// The warnings for unused fields. /// </summary> private ImmutableArray<Diagnostic> _unusedFieldWarnings; internal SourceAssemblySymbol( CSharpCompilation compilation, string assemblySimpleName, string moduleName, ImmutableArray<PEModule> netModules) { Debug.Assert(compilation != null); Debug.Assert(assemblySimpleName != null); Debug.Assert(!String.IsNullOrWhiteSpace(moduleName)); Debug.Assert(!netModules.IsDefault); _compilation = compilation; _assemblySimpleName = assemblySimpleName; ArrayBuilder<ModuleSymbol> moduleBuilder = new ArrayBuilder<ModuleSymbol>(1 + netModules.Length); moduleBuilder.Add(new SourceModuleSymbol(this, compilation.Declarations, moduleName)); var importOptions = (compilation.Options.MetadataImportOptions == MetadataImportOptions.All) ? MetadataImportOptions.All : MetadataImportOptions.Internal; foreach (PEModule netModule in netModules) { moduleBuilder.Add(new PEModuleSymbol(this, netModule, importOptions, moduleBuilder.Count)); // SetReferences will be called later by the ReferenceManager (in CreateSourceAssemblyFullBind for // a fresh manager, in CreateSourceAssemblyReuseData for a reused one). } _modules = moduleBuilder.ToImmutableAndFree(); if (!compilation.Options.CryptoPublicKey.IsEmpty) { // Private key is not necessary for assembly identity, only when emitting. For this reason, the private key can remain null. _lazyStrongNameKeys = StrongNameKeys.Create(compilation.Options.CryptoPublicKey, privateKey: null, hasCounterSignature: false, MessageProvider.Instance); } } public override string Name { get { return _assemblySimpleName; } } /// <remarks> /// This override is essential - it's a base case of the recursive definition. /// </remarks> internal sealed override CSharpCompilation DeclaringCompilation { get { return _compilation; } } public override bool IsInteractive { get { return _compilation.IsSubmission; } } internal bool MightContainNoPiaLocalTypes() { for (int i = 1; i < _modules.Length; i++) { var peModuleSymbol = (Metadata.PE.PEModuleSymbol)_modules[i]; if (peModuleSymbol.Module.ContainsNoPiaLocalTypes()) { return true; } } return SourceModule.MightContainNoPiaLocalTypes(); } public override AssemblyIdentity Identity { get { if (lazyAssemblyIdentity == null) Interlocked.CompareExchange(ref lazyAssemblyIdentity, ComputeIdentity(), null); return lazyAssemblyIdentity; } } internal override Symbol GetSpecialTypeMember(SpecialMember member) { return _compilation.IsMemberMissing(member) ? null : base.GetSpecialTypeMember(member); } #nullable enable private string? GetWellKnownAttributeDataStringField(Func<CommonAssemblyWellKnownAttributeData, string> fieldGetter, string? missingValue = null, QuickAttributes? attributeMatchesOpt = null) { string? fieldValue = missingValue; var data = attributeMatchesOpt is null ? GetSourceDecodedWellKnownAttributeData() : GetSourceDecodedWellKnownAttributeData(attributeMatchesOpt.Value); if (data != null) { fieldValue = fieldGetter(data); } if (fieldValue == (object?)missingValue) { data = (attributeMatchesOpt is null || _lazyNetModuleAttributesBag is not null) ? GetNetModuleDecodedWellKnownAttributeData() : GetLimitedNetModuleDecodedWellKnownAttributeData(attributeMatchesOpt.Value); if (data != null) { fieldValue = fieldGetter(data); } } return fieldValue; } #nullable disable internal bool RuntimeCompatibilityWrapNonExceptionThrows { get { var data = GetSourceDecodedWellKnownAttributeData() ?? GetNetModuleDecodedWellKnownAttributeData(); // By default WrapNonExceptionThrows is considered to be true. return (data != null) ? data.RuntimeCompatibilityWrapNonExceptionThrows : CommonAssemblyWellKnownAttributeData.WrapNonExceptionThrowsDefault; } } internal string FileVersion { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyFileVersionAttributeSetting); } } internal string Title { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyTitleAttributeSetting); } } internal string Description { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyDescriptionAttributeSetting); } } internal string Company { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyCompanyAttributeSetting); } } internal string Product { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyProductAttributeSetting); } } internal string InformationalVersion { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyInformationalVersionAttributeSetting); } } internal string Copyright { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyCopyrightAttributeSetting); } } internal string Trademark { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyTrademarkAttributeSetting); } } private ThreeState AssemblyDelaySignAttributeSetting { get { var defaultValue = ThreeState.Unknown; var fieldValue = defaultValue; var data = GetSourceDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyDelaySignAttributeSetting; } if (fieldValue == defaultValue) { data = GetNetModuleDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyDelaySignAttributeSetting; } } return fieldValue; } } private string AssemblyKeyContainerAttributeSetting { get { // We mitigate circularity problems by only actively loading attributes that pass a syntactic check return GetWellKnownAttributeDataStringField(data => data.AssemblyKeyContainerAttributeSetting, WellKnownAttributeData.StringMissingValue, QuickAttributes.AssemblyKeyName); } } private string AssemblyKeyFileAttributeSetting { get { // We mitigate circularity problems by only actively loading attributes that pass a syntactic check return GetWellKnownAttributeDataStringField(data => data.AssemblyKeyFileAttributeSetting, WellKnownAttributeData.StringMissingValue, QuickAttributes.AssemblyKeyFile); } } private string AssemblyCultureAttributeSetting { get { return GetWellKnownAttributeDataStringField(data => data.AssemblyCultureAttributeSetting); } } public string SignatureKey { get { // We mitigate circularity problems by only actively loading attributes that pass a syntactic check return GetWellKnownAttributeDataStringField(data => data.AssemblySignatureKeyAttributeSetting, missingValue: null, QuickAttributes.AssemblySignatureKey); } } private Version AssemblyVersionAttributeSetting { get { var defaultValue = (Version)null; var fieldValue = defaultValue; var data = GetSourceDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyVersionAttributeSetting; } if (fieldValue == defaultValue) { data = GetNetModuleDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyVersionAttributeSetting; } } return fieldValue; } } public override Version AssemblyVersionPattern { get { var attributeValue = AssemblyVersionAttributeSetting; return (object)attributeValue == null || (attributeValue.Build != ushort.MaxValue && attributeValue.Revision != ushort.MaxValue) ? null : attributeValue; } } public AssemblyHashAlgorithm HashAlgorithm { get { return AssemblyAlgorithmIdAttributeSetting ?? AssemblyHashAlgorithm.Sha1; } } internal AssemblyHashAlgorithm? AssemblyAlgorithmIdAttributeSetting { get { var fieldValue = (AssemblyHashAlgorithm?)null; var data = GetSourceDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyAlgorithmIdAttributeSetting; } if (!fieldValue.HasValue) { data = GetNetModuleDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyAlgorithmIdAttributeSetting; } } return fieldValue; } } /// <summary> /// This represents what the user claimed in source through the AssemblyFlagsAttribute. /// It may be modified as emitted due to presence or absence of the public key. /// </summary> public AssemblyFlags AssemblyFlags { get { var defaultValue = default(AssemblyFlags); var fieldValue = defaultValue; var data = GetSourceDecodedWellKnownAttributeData(); if (data != null) { fieldValue = data.AssemblyFlagsAttributeSetting; } data = GetNetModuleDecodedWellKnownAttributeData(); if (data != null) { fieldValue |= data.AssemblyFlagsAttributeSetting; } return fieldValue; } } private StrongNameKeys ComputeStrongNameKeys() { // when both attributes and command-line options specified, cmd line wins. string keyFile = _compilation.Options.CryptoKeyFile; // Public sign requires a keyfile if (DeclaringCompilation.Options.PublicSign) { // TODO(https://github.com/dotnet/roslyn/issues/9150): // Provide better error message if keys are provided by // the attributes. Right now we'll just fall through to the // "no key available" error. if (!string.IsNullOrEmpty(keyFile) && !PathUtilities.IsAbsolute(keyFile)) { // If keyFile has a relative path then there should be a diagnostic // about it Debug.Assert(!DeclaringCompilation.Options.Errors.IsEmpty); return StrongNameKeys.None; } // If we're public signing, we don't need a strong name provider return StrongNameKeys.Create(keyFile, MessageProvider.Instance); } if (string.IsNullOrEmpty(keyFile)) { keyFile = this.AssemblyKeyFileAttributeSetting; if ((object)keyFile == (object)WellKnownAttributeData.StringMissingValue) { keyFile = null; } } string keyContainer = _compilation.Options.CryptoKeyContainer; if (string.IsNullOrEmpty(keyContainer)) { keyContainer = this.AssemblyKeyContainerAttributeSetting; if ((object)keyContainer == (object)WellKnownAttributeData.StringMissingValue) { keyContainer = null; } } var hasCounterSignature = !string.IsNullOrEmpty(this.SignatureKey); return StrongNameKeys.Create(DeclaringCompilation.Options.StrongNameProvider, keyFile, keyContainer, hasCounterSignature, MessageProvider.Instance); } // A collection of assemblies to which we were granted internals access by only checking matches for assembly name // and ignoring public key. This just acts as a set. The bool is ignored. private ConcurrentDictionary<AssemblySymbol, bool> _optimisticallyGrantedInternalsAccess; //EDMAURER please don't use thread local storage widely. This is hoped to be a one-off usage. [ThreadStatic] private static AssemblySymbol t_assemblyForWhichCurrentThreadIsComputingKeys; internal StrongNameKeys StrongNameKeys { get { if (_lazyStrongNameKeys == null) { try { t_assemblyForWhichCurrentThreadIsComputingKeys = this; Interlocked.CompareExchange(ref _lazyStrongNameKeys, ComputeStrongNameKeys(), null); } finally { t_assemblyForWhichCurrentThreadIsComputingKeys = null; } } return _lazyStrongNameKeys; } } internal override ImmutableArray<byte> PublicKey { get { return StrongNameKeys.PublicKey; } } public override ImmutableArray<ModuleSymbol> Modules { get { return _modules; } } //TODO: cache public override ImmutableArray<Location> Locations { get { return this.Modules.SelectMany(m => m.Locations).AsImmutable(); } } private void ValidateAttributeSemantics(BindingDiagnosticBag diagnostics) { //diagnostics that come from computing the public key. //If building a netmodule, strong name keys need not be validated. Dev11 didn't. if (StrongNameKeys.DiagnosticOpt != null && !_compilation.Options.OutputKind.IsNetModule()) { diagnostics.Add(StrongNameKeys.DiagnosticOpt); } ValidateIVTPublicKeys(diagnostics); //diagnostics that result from IVT checks performed while in the process of computing the public key. CheckOptimisticIVTAccessGrants(diagnostics); DetectAttributeAndOptionConflicts(diagnostics); if (IsDelaySigned && !Identity.HasPublicKey) { diagnostics.Add(ErrorCode.WRN_DelaySignButNoKey, NoLocation.Singleton); } if (DeclaringCompilation.Options.PublicSign) { if (_compilation.Options.OutputKind.IsNetModule()) { diagnostics.Add(ErrorCode.ERR_PublicSignNetModule, NoLocation.Singleton); } else if (!Identity.HasPublicKey) { diagnostics.Add(ErrorCode.ERR_PublicSignButNoKey, NoLocation.Singleton); } } // If the options and attributes applied on the compilation imply real signing, // but we have no private key to sign it with report an error. // Note that if public key is set and delay sign is off we do OSS signing, which doesn't require private key. // Consider: should we allow to OSS sign if the key file only contains public key? if (DeclaringCompilation.Options.OutputKind != OutputKind.NetModule && DeclaringCompilation.Options.CryptoPublicKey.IsEmpty && Identity.HasPublicKey && !IsDelaySigned && !DeclaringCompilation.Options.PublicSign && !StrongNameKeys.CanSign && StrongNameKeys.DiagnosticOpt == null) { // Since the container always contains both keys, the problem is that the key file didn't contain private key. diagnostics.Add(ErrorCode.ERR_SignButNoPrivateKey, NoLocation.Singleton, StrongNameKeys.KeyFilePath); } ReportDiagnosticsForSynthesizedAttributes(_compilation, diagnostics); } /// <summary> /// We're going to synthesize some well-known attributes for this assembly symbol. However, at synthesis time, it is /// too late to report diagnostics or cancel the emit. Instead, we check for use site errors on the types and members /// we know we'll need at synthesis time. /// </summary> /// <remarks> /// As in Dev10, we won't report anything if the attribute TYPES are missing (note: missing, not erroneous) because we won't /// synthesize anything in that case. We'll only report diagnostics if the attribute TYPES are present and either they or /// the attribute CONSTRUCTORS have errors. /// </remarks> private static void ReportDiagnosticsForSynthesizedAttributes(CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { ReportDiagnosticsForUnsafeSynthesizedAttributes(compilation, diagnostics); CSharpCompilationOptions compilationOptions = compilation.Options; if (!compilationOptions.OutputKind.IsNetModule()) { TypeSymbol compilationRelaxationsAttribute = compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute); Debug.Assert((object)compilationRelaxationsAttribute != null, "GetWellKnownType unexpectedly returned null"); if (!(compilationRelaxationsAttribute is MissingMetadataTypeSymbol)) { // As in Dev10 (see GlobalAttrBind::EmitCompilerGeneratedAttrs), we only synthesize this attribute if CompilationRelaxationsAttribute is found. Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32, diagnostics, NoLocation.Singleton); } TypeSymbol runtimeCompatibilityAttribute = compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute); Debug.Assert((object)runtimeCompatibilityAttribute != null, "GetWellKnownType unexpectedly returned null"); if (!(runtimeCompatibilityAttribute is MissingMetadataTypeSymbol)) { // As in Dev10 (see GlobalAttrBind::EmitCompilerGeneratedAttrs), we only synthesize this attribute if RuntimeCompatibilityAttribute is found. Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor, diagnostics, NoLocation.Singleton); Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows, diagnostics, NoLocation.Singleton); } } } /// <summary> /// If this compilation allows unsafe code (note: allows, not contains), then when we actually emit the assembly/module, /// we're going to synthesize SecurityPermissionAttribute/UnverifiableCodeAttribute. However, at synthesis time, it is /// too late to report diagnostics or cancel the emit. Instead, we check for use site errors on the types and members /// we know we'll need at synthesis time. /// </summary> /// <remarks> /// As in Dev10, we won't report anything if the attribute TYPES are missing (note: missing, not erroneous) because we won't /// synthesize anything in that case. We'll only report diagnostics if the attribute TYPES are present and either they or /// the attribute CONSTRUCTORS have errors. /// </remarks> private static void ReportDiagnosticsForUnsafeSynthesizedAttributes(CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { CSharpCompilationOptions compilationOptions = compilation.Options; if (!compilationOptions.AllowUnsafe) { return; } TypeSymbol unverifiableCodeAttribute = compilation.GetWellKnownType(WellKnownType.System_Security_UnverifiableCodeAttribute); Debug.Assert((object)unverifiableCodeAttribute != null, "GetWellKnownType unexpectedly returned null"); if (unverifiableCodeAttribute is MissingMetadataTypeSymbol) { return; } // As in Dev10 (see GlobalAttrBind::EmitCompilerGeneratedAttrs), we only synthesize this attribute if // UnverifiableCodeAttribute is found. Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Security_UnverifiableCodeAttribute__ctor, diagnostics, NoLocation.Singleton); TypeSymbol securityPermissionAttribute = compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityPermissionAttribute); Debug.Assert((object)securityPermissionAttribute != null, "GetWellKnownType unexpectedly returned null"); if (securityPermissionAttribute is MissingMetadataTypeSymbol) { return; } TypeSymbol securityAction = compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction); Debug.Assert((object)securityAction != null, "GetWellKnownType unexpectedly returned null"); if (securityAction is MissingMetadataTypeSymbol) { return; } // As in Dev10 (see GlobalAttrBind::EmitCompilerGeneratedAttrs), we only synthesize this attribute if // UnverifiableCodeAttribute, SecurityAction, and SecurityPermissionAttribute are found. Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Security_Permissions_SecurityPermissionAttribute__ctor, diagnostics, NoLocation.Singleton); // Not actually an attribute, but the same logic applies. Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(compilation, WellKnownMember.System_Security_Permissions_SecurityPermissionAttribute__SkipVerification, diagnostics, NoLocation.Singleton); } private void ValidateIVTPublicKeys(BindingDiagnosticBag diagnostics) { EnsureAttributesAreBound(); if (!this.Identity.IsStrongName) return; if (_lazyInternalsVisibleToMap != null) { foreach (var keys in _lazyInternalsVisibleToMap.Values) { foreach (var oneKey in keys) { if (oneKey.Key.IsDefaultOrEmpty) { diagnostics.Add(ErrorCode.ERR_FriendAssemblySNReq, oneKey.Value.Item1, oneKey.Value.Item2); } } } } } /// <summary> /// True if internals are exposed at all. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// This property shouldn't be accessed during binding as it can lead to attribute binding cycle. /// </remarks> public bool InternalsAreVisible { get { EnsureAttributesAreBound(); return _lazyInternalsVisibleToMap != null; } } private void DetectAttributeAndOptionConflicts(BindingDiagnosticBag diagnostics) { EnsureAttributesAreBound(); ThreeState assemblyDelaySignAttributeSetting = this.AssemblyDelaySignAttributeSetting; if (_compilation.Options.DelaySign.HasValue && (assemblyDelaySignAttributeSetting != ThreeState.Unknown) && (DeclaringCompilation.Options.DelaySign.Value != (assemblyDelaySignAttributeSetting == ThreeState.True))) { diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, NoLocation.Singleton, "DelaySign", AttributeDescription.AssemblyDelaySignAttribute.FullName); } if (_compilation.Options.PublicSign && assemblyDelaySignAttributeSetting == ThreeState.True) { diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, NoLocation.Singleton, nameof(_compilation.Options.PublicSign), AttributeDescription.AssemblyDelaySignAttribute.FullName); } if (!String.IsNullOrEmpty(_compilation.Options.CryptoKeyContainer)) { string assemblyKeyContainerAttributeSetting = this.AssemblyKeyContainerAttributeSetting; if ((object)assemblyKeyContainerAttributeSetting == (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { if (_compilation.Options.OutputKind == OutputKind.NetModule) { // We need to synthesize this attribute for .NET module, // touch the constructor in order to generate proper use-site diagnostics Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(_compilation, WellKnownMember.System_Reflection_AssemblyKeyNameAttribute__ctor, diagnostics, NoLocation.Singleton); } } else if (String.Compare(_compilation.Options.CryptoKeyContainer, assemblyKeyContainerAttributeSetting, StringComparison.OrdinalIgnoreCase) != 0) { // Native compiler reports a warning in this case, notifying the user that attribute value from source is ignored, // but it doesn't drop the attribute during emit. That might be fine if we produce an assembly because we actually sign it with correct // key (the one from compilation options) without relying on the emitted attribute. // If we are building a .NET module, things get more complicated. In particular, we don't sign the module, we emit an attribute with the key // information, which will be used to sign an assembly once the module is linked into it. If there is already an attribute like that in source, // native compiler emits both of them, synthetic attribute is emitted after the one from source. Incidentally, ALink picks the last attribute // for signing and things seem to work out. However, relying on the order of attributes feels fragile, especially given that Roslyn emits // synthetic attributes before attributes from source. The behavior we settled on for .NET modules is that, if the attribute in source has the // same value as the one in compilation options, we won't emit the synthetic attribute. If the value doesn't match, we report an error, which // is a breaking change. Bottom line, we will never produce a module or an assembly with two attributes, regardless whether values are the same // or not. if (_compilation.Options.OutputKind == OutputKind.NetModule) { diagnostics.Add(ErrorCode.ERR_CmdOptionConflictsSource, NoLocation.Singleton, AttributeDescription.AssemblyKeyNameAttribute.FullName, "CryptoKeyContainer"); } else { diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, NoLocation.Singleton, "CryptoKeyContainer", AttributeDescription.AssemblyKeyNameAttribute.FullName); } } } if (_compilation.Options.PublicSign && !_compilation.Options.OutputKind.IsNetModule() && (object)this.AssemblyKeyContainerAttributeSetting != (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { diagnostics.Add(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning, NoLocation.Singleton, AttributeDescription.AssemblyKeyNameAttribute.FullName); } if (!String.IsNullOrEmpty(_compilation.Options.CryptoKeyFile)) { string assemblyKeyFileAttributeSetting = this.AssemblyKeyFileAttributeSetting; if ((object)assemblyKeyFileAttributeSetting == (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { if (_compilation.Options.OutputKind == OutputKind.NetModule) { // We need to synthesize this attribute for .NET module, // touch the constructor in order to generate proper use-site diagnostics Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(_compilation, WellKnownMember.System_Reflection_AssemblyKeyFileAttribute__ctor, diagnostics, NoLocation.Singleton); } } else if (String.Compare(_compilation.Options.CryptoKeyFile, assemblyKeyFileAttributeSetting, StringComparison.OrdinalIgnoreCase) != 0) { // Comment in similar section for CryptoKeyContainer is applicable here as well. if (_compilation.Options.OutputKind == OutputKind.NetModule) { diagnostics.Add(ErrorCode.ERR_CmdOptionConflictsSource, NoLocation.Singleton, AttributeDescription.AssemblyKeyFileAttribute.FullName, "CryptoKeyFile"); } else { diagnostics.Add(ErrorCode.WRN_CmdOptionConflictsSource, NoLocation.Singleton, "CryptoKeyFile", AttributeDescription.AssemblyKeyFileAttribute.FullName); } } } if (_compilation.Options.PublicSign && !_compilation.Options.OutputKind.IsNetModule() && (object)this.AssemblyKeyFileAttributeSetting != (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { diagnostics.Add(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning, NoLocation.Singleton, AttributeDescription.AssemblyKeyFileAttribute.FullName); } } internal bool IsDelaySigned { get { //commandline setting trumps attribute value. Warning assumed to be given elsewhere if (_compilation.Options.DelaySign.HasValue) { return _compilation.Options.DelaySign.Value; } // The public sign argument should also override the attribute if (_compilation.Options.PublicSign) { return false; } return (this.AssemblyDelaySignAttributeSetting == ThreeState.True); } } internal SourceModuleSymbol SourceModule { get { return (SourceModuleSymbol)this.Modules[0]; } } internal override bool RequiresCompletion { get { return true; } } internal override bool HasComplete(CompletionPart part) { return _state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: EnsureAttributesAreBound(); break; case CompletionPart.StartAttributeChecks: case CompletionPart.FinishAttributeChecks: if (_state.NotePartComplete(CompletionPart.StartAttributeChecks)) { var diagnostics = BindingDiagnosticBag.GetInstance(); ValidateAttributeSemantics(diagnostics); AddDeclarationDiagnostics(diagnostics); var thisThreadCompleted = _state.NotePartComplete(CompletionPart.FinishAttributeChecks); Debug.Assert(thisThreadCompleted); diagnostics.Free(); } break; case CompletionPart.Module: SourceModule.ForceComplete(locationOpt, cancellationToken); if (SourceModule.HasComplete(CompletionPart.MembersCompleted)) { _state.NotePartComplete(CompletionPart.Module); break; } else { Debug.Assert(locationOpt != null, "If no location was specified, then the module members should be completed"); // this is the last completion part we can handle if there is a location. return; } case CompletionPart.StartValidatingAddedModules: case CompletionPart.FinishValidatingAddedModules: if (_state.NotePartComplete(CompletionPart.StartValidatingAddedModules)) { ReportDiagnosticsForAddedModules(); var thisThreadCompleted = _state.NotePartComplete(CompletionPart.FinishValidatingAddedModules); Debug.Assert(thisThreadCompleted); } break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(CompletionPart.All & ~CompletionPart.AssemblySymbolAll); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } } private void ReportDiagnosticsForAddedModules() { var diagnostics = BindingDiagnosticBag.GetInstance(); foreach (var pair in _compilation.GetBoundReferenceManager().ReferencedModuleIndexMap) { var fileRef = pair.Key as PortableExecutableReference; if ((object)fileRef != null && (object)fileRef.FilePath != null) { string fileName = FileNameUtilities.GetFileName(fileRef.FilePath); string moduleName = _modules[pair.Value].Name; if (!string.Equals(fileName, moduleName, StringComparison.OrdinalIgnoreCase)) { // Used to be ERR_ALinkFailed diagnostics.Add(ErrorCode.ERR_NetModuleNameMismatch, NoLocation.Singleton, moduleName, fileName); } } } // Alink performed these checks only when emitting an assembly. if (_modules.Length > 1 && !_compilation.Options.OutputKind.IsNetModule()) { var assemblyMachine = this.Machine; bool isPlatformAgnostic = (assemblyMachine == System.Reflection.PortableExecutable.Machine.I386 && !this.Bit32Required); var knownModuleNames = new HashSet<String>(StringComparer.OrdinalIgnoreCase); for (int i = 1; i < _modules.Length; i++) { ModuleSymbol m = _modules[i]; if (!knownModuleNames.Add(m.Name)) { diagnostics.Add(ErrorCode.ERR_NetModuleNameMustBeUnique, NoLocation.Singleton, m.Name); } if (!((PEModuleSymbol)m).Module.IsCOFFOnly) { var moduleMachine = m.Machine; if (moduleMachine == System.Reflection.PortableExecutable.Machine.I386 && !m.Bit32Required) { // Other module is agnostic, this is always safe ; } else if (isPlatformAgnostic) { diagnostics.Add(ErrorCode.ERR_AgnosticToMachineModule, NoLocation.Singleton, m); } else if (assemblyMachine != moduleMachine) { // Different machine types, and neither is agnostic // So it is a conflict diagnostics.Add(ErrorCode.ERR_ConflictingMachineModule, NoLocation.Singleton, m); } } } // Assembly main module must explicitly reference all the modules referenced by other assembly // modules, i.e. all modules from transitive closure must be referenced explicitly here for (int i = 1; i < _modules.Length; i++) { var m = (PEModuleSymbol)_modules[i]; try { foreach (var referencedModuleName in m.Module.GetReferencedManagedModulesOrThrow()) { // Do not report error for this module twice if (knownModuleNames.Add(referencedModuleName)) { diagnostics.Add(ErrorCode.ERR_MissingNetModuleReference, NoLocation.Singleton, referencedModuleName); } } } catch (BadImageFormatException) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, m), NoLocation.Singleton); } } } ReportNameCollisionDiagnosticsForAddedModules(this.GlobalNamespace, diagnostics); AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); } private void ReportNameCollisionDiagnosticsForAddedModules(NamespaceSymbol ns, BindingDiagnosticBag diagnostics) { var mergedNs = ns as MergedNamespaceSymbol; if ((object)mergedNs == null) { return; } ImmutableArray<NamespaceSymbol> constituent = mergedNs.ConstituentNamespaces; if (constituent.Length > 2 || (constituent.Length == 2 && constituent[0].ContainingModule.Ordinal != 0 && constituent[1].ContainingModule.Ordinal != 0)) { var topLevelTypesFromModules = ArrayBuilder<NamedTypeSymbol>.GetInstance(); foreach (var moduleNs in constituent) { Debug.Assert(moduleNs.Extent.Kind == NamespaceKind.Module); if (moduleNs.ContainingModule.Ordinal != 0) { topLevelTypesFromModules.AddRange(moduleNs.GetTypeMembers()); } } topLevelTypesFromModules.Sort(NameCollisionForAddedModulesTypeComparer.Singleton); bool reportedAnError = false; for (int i = 0; i < topLevelTypesFromModules.Count - 1; i++) { NamedTypeSymbol x = topLevelTypesFromModules[i]; NamedTypeSymbol y = topLevelTypesFromModules[i + 1]; if (x.Arity == y.Arity && x.Name == y.Name) { if (!reportedAnError) { // Skip synthetic <Module> type which every .NET module has. if (x.Arity != 0 || !x.ContainingNamespace.IsGlobalNamespace || x.Name != "<Module>") { diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, y.Locations.FirstOrNone(), y.ToDisplayString(SymbolDisplayFormat.ShortFormat), y.ContainingNamespace); } reportedAnError = true; } } else { reportedAnError = false; } } topLevelTypesFromModules.Free(); // Descent into child namespaces. foreach (Symbol member in mergedNs.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { ReportNameCollisionDiagnosticsForAddedModules((NamespaceSymbol)member, diagnostics); } } } } private class NameCollisionForAddedModulesTypeComparer : IComparer<NamedTypeSymbol> { public static readonly NameCollisionForAddedModulesTypeComparer Singleton = new NameCollisionForAddedModulesTypeComparer(); private NameCollisionForAddedModulesTypeComparer() { } public int Compare(NamedTypeSymbol x, NamedTypeSymbol y) { int result = String.CompareOrdinal(x.Name, y.Name); if (result == 0) { result = x.Arity - y.Arity; if (result == 0) { result = x.ContainingModule.Ordinal - y.ContainingModule.Ordinal; } } return result; } } private bool IsKnownAssemblyAttribute(CSharpAttributeData attribute) { // TODO: This list used to include AssemblyOperatingSystemAttribute and AssemblyProcessorAttribute, // but it doesn't look like they are defined, cannot find them on MSDN. if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTitleAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDescriptionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyConfigurationAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCultureAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCompanyAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyProductAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyInformationalVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCopyrightAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTrademarkAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyFileAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyNameAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyAlgorithmIdAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyFlagsAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDelaySignAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblyFileVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.SatelliteContractVersionAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.AssemblySignatureKeyAttribute)) { return true; } return false; } private void AddOmittedAttributeIndex(int index) { if (_lazyOmittedAttributeIndices == null) { Interlocked.CompareExchange(ref _lazyOmittedAttributeIndices, new ConcurrentSet<int>(), null); } _lazyOmittedAttributeIndices.Add(index); } /// <summary> /// Gets unique source assembly attributes that should be emitted, /// i.e. filters out attributes with errors and duplicate attributes. /// </summary> private HashSet<CSharpAttributeData> GetUniqueSourceAssemblyAttributes() { ImmutableArray<CSharpAttributeData> appliedSourceAttributes = this.GetSourceAttributesBag().Attributes; HashSet<CSharpAttributeData> uniqueAttributes = null; for (int i = 0; i < appliedSourceAttributes.Length; i++) { CSharpAttributeData attribute = appliedSourceAttributes[i]; if (!attribute.HasErrors) { if (!AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes)) { AddOmittedAttributeIndex(i); } } } return uniqueAttributes; } private static bool AddUniqueAssemblyAttribute(CSharpAttributeData attribute, ref HashSet<CSharpAttributeData> uniqueAttributes) { Debug.Assert(!attribute.HasErrors); if (uniqueAttributes == null) { uniqueAttributes = new HashSet<CSharpAttributeData>(comparer: CommonAttributeDataComparer.Instance); } return uniqueAttributes.Add(attribute); } private bool ValidateAttributeUsageForNetModuleAttribute(CSharpAttributeData attribute, string netModuleName, BindingDiagnosticBag diagnostics, ref HashSet<CSharpAttributeData> uniqueAttributes) { Debug.Assert(!attribute.HasErrors); var attributeClass = attribute.AttributeClass; if (attributeClass.GetAttributeUsageInfo().AllowMultiple) { // Duplicate attributes are allowed, but native compiler doesn't emit duplicate attributes, i.e. attributes with same constructor and arguments. return AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes); } else { // Duplicate attributes with same attribute type are not allowed. // Check if there is an existing assembly attribute with same attribute type. if (uniqueAttributes == null || !uniqueAttributes.Contains((a) => TypeSymbol.Equals(a.AttributeClass, attributeClass, TypeCompareKind.ConsiderEverything2))) { // Attribute with unique attribute type, not a duplicate. bool success = AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes); Debug.Assert(success); return true; } else { // Duplicate attribute with same attribute type, we should report an error. // Native compiler suppresses the error for // (a) Duplicate well-known assembly attributes and // (b) Identical duplicates, i.e. attributes with same constructor and arguments. // For (a), native compiler picks the last of these duplicate well-known netmodule attributes, but these can vary based on the ordering of referenced netmodules. if (IsKnownAssemblyAttribute(attribute)) { if (!uniqueAttributes.Contains(attribute)) { // This attribute application will be ignored. diagnostics.Add(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden, NoLocation.Singleton, attribute.AttributeClass, netModuleName); } } else if (AddUniqueAssemblyAttribute(attribute, ref uniqueAttributes)) { // Error diagnostics.Add(ErrorCode.ERR_DuplicateAttributeInNetModule, NoLocation.Singleton, attribute.AttributeClass.Name, netModuleName); } return false; } } // CONSIDER Handling badly targeted assembly attributes from netmodules //if (!badDuplicateAttribute && ((attributeUsageInfo.ValidTargets & AttributeTargets.Assembly) == 0)) //{ // // Error and skip // diagnostics.Add(ErrorCode.ERR_AttributeOnBadSymbolTypeInNetModule, NoLocation.Singleton, attribute.AttributeClass.Name, netModuleName, attributeUsageInfo.GetValidTargetsString()); // return false; //} } private ImmutableArray<CSharpAttributeData> GetNetModuleAttributes(out ImmutableArray<string> netModuleNames) { ArrayBuilder<CSharpAttributeData> moduleAssemblyAttributesBuilder = null; ArrayBuilder<string> netModuleNameBuilder = null; for (int i = 1; i < _modules.Length; i++) { var peModuleSymbol = (Metadata.PE.PEModuleSymbol)_modules[i]; string netModuleName = peModuleSymbol.Name; foreach (var attributeData in peModuleSymbol.GetAssemblyAttributes()) { if (netModuleNameBuilder == null) { netModuleNameBuilder = ArrayBuilder<string>.GetInstance(); moduleAssemblyAttributesBuilder = ArrayBuilder<CSharpAttributeData>.GetInstance(); } netModuleNameBuilder.Add(netModuleName); moduleAssemblyAttributesBuilder.Add(attributeData); } } if (netModuleNameBuilder == null) { netModuleNames = ImmutableArray<string>.Empty; return ImmutableArray<CSharpAttributeData>.Empty; } netModuleNames = netModuleNameBuilder.ToImmutableAndFree(); return moduleAssemblyAttributesBuilder.ToImmutableAndFree(); } private WellKnownAttributeData ValidateAttributeUsageAndDecodeWellKnownAttributes( ImmutableArray<CSharpAttributeData> attributesFromNetModules, ImmutableArray<string> netModuleNames, BindingDiagnosticBag diagnostics) { Debug.Assert(attributesFromNetModules.Any()); Debug.Assert(netModuleNames.Any()); Debug.Assert(attributesFromNetModules.Length == netModuleNames.Length); int netModuleAttributesCount = attributesFromNetModules.Length; int sourceAttributesCount = this.GetSourceAttributesBag().Attributes.Length; // Get unique source assembly attributes. HashSet<CSharpAttributeData> uniqueAttributes = GetUniqueSourceAssemblyAttributes(); var arguments = new DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation>(); arguments.AttributesCount = netModuleAttributesCount; arguments.Diagnostics = diagnostics; arguments.SymbolPart = AttributeLocation.None; // Attributes from the second added module should override attributes from the first added module, etc. // Attributes from source should override attributes from added modules. // That is why we are iterating attributes backwards. for (int i = netModuleAttributesCount - 1; i >= 0; i--) { var totalIndex = i + sourceAttributesCount; CSharpAttributeData attribute = attributesFromNetModules[i]; if (!attribute.HasErrors && ValidateAttributeUsageForNetModuleAttribute(attribute, netModuleNames[i], diagnostics, ref uniqueAttributes)) { arguments.Attribute = attribute; arguments.Index = i; // CONSIDER: Provide usable AttributeSyntax node for diagnostics of malformed netmodule assembly attributes arguments.AttributeSyntaxOpt = null; this.DecodeWellKnownAttribute(ref arguments, totalIndex, isFromNetModule: true); } else { AddOmittedAttributeIndex(totalIndex); } } return arguments.HasDecodedData ? arguments.DecodedData : null; } private void LoadAndValidateNetModuleAttributes(ref CustomAttributesBag<CSharpAttributeData> lazyNetModuleAttributesBag) { if (_compilation.Options.OutputKind.IsNetModule()) { Interlocked.CompareExchange(ref lazyNetModuleAttributesBag, CustomAttributesBag<CSharpAttributeData>.Empty, null); } else { var diagnostics = BindingDiagnosticBag.GetInstance(); ImmutableArray<string> netModuleNames; ImmutableArray<CSharpAttributeData> attributesFromNetModules = GetNetModuleAttributes(out netModuleNames); WellKnownAttributeData wellKnownData = null; if (attributesFromNetModules.Any()) { wellKnownData = ValidateAttributeUsageAndDecodeWellKnownAttributes(attributesFromNetModules, netModuleNames, diagnostics); } else { // Compute duplicate source assembly attributes, i.e. attributes with same constructor and arguments, that must not be emitted. var unused = GetUniqueSourceAssemblyAttributes(); } // Load type forwarders from modules HashSet<NamedTypeSymbol> forwardedTypes = null; // Similar to attributes, type forwarders from the second added module should override type forwarders from the first added module, etc. // This affects only diagnostics. for (int i = _modules.Length - 1; i > 0; i--) { var peModuleSymbol = (Metadata.PE.PEModuleSymbol)_modules[i]; foreach (NamedTypeSymbol forwarded in peModuleSymbol.GetForwardedTypes()) { if (forwardedTypes == null) { if (wellKnownData == null) { wellKnownData = new CommonAssemblyWellKnownAttributeData(); } forwardedTypes = ((CommonAssemblyWellKnownAttributeData)wellKnownData).ForwardedTypes; if (forwardedTypes == null) { forwardedTypes = new HashSet<NamedTypeSymbol>(); ((CommonAssemblyWellKnownAttributeData)wellKnownData).ForwardedTypes = forwardedTypes; } } if (forwardedTypes.Add(forwarded)) { if (forwarded.IsErrorType()) { if (!diagnostics.ReportUseSite(forwarded, NoLocation.Singleton)) { DiagnosticInfo info = ((ErrorTypeSymbol)forwarded).ErrorInfo; if ((object)info != null) { diagnostics.Add(info, NoLocation.Singleton); } } } } } } CustomAttributesBag<CSharpAttributeData> netModuleAttributesBag; if (wellKnownData != null || attributesFromNetModules.Any()) { netModuleAttributesBag = new CustomAttributesBag<CSharpAttributeData>(); netModuleAttributesBag.SetEarlyDecodedWellKnownAttributeData(null); netModuleAttributesBag.SetDecodedWellKnownAttributeData(wellKnownData); netModuleAttributesBag.SetAttributes(attributesFromNetModules); if (netModuleAttributesBag.IsEmpty) netModuleAttributesBag = CustomAttributesBag<CSharpAttributeData>.Empty; } else { netModuleAttributesBag = CustomAttributesBag<CSharpAttributeData>.Empty; } if (Interlocked.CompareExchange(ref lazyNetModuleAttributesBag, netModuleAttributesBag, null) == null) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); Debug.Assert(lazyNetModuleAttributesBag.IsSealed); } } private CommonAssemblyWellKnownAttributeData GetLimitedNetModuleDecodedWellKnownAttributeData(QuickAttributes attributeMatches) { Debug.Assert(attributeMatches is QuickAttributes.AssemblyKeyFile or QuickAttributes.AssemblyKeyName or QuickAttributes.AssemblySignatureKey); if (_compilation.Options.OutputKind.IsNetModule()) { return null; } ImmutableArray<string> netModuleNames; ImmutableArray<CSharpAttributeData> attributesFromNetModules = GetNetModuleAttributes(out netModuleNames); WellKnownAttributeData wellKnownData = null; if (attributesFromNetModules.Any()) { wellKnownData = limitedDecodeWellKnownAttributes(attributesFromNetModules, netModuleNames, attributeMatches); } return (CommonAssemblyWellKnownAttributeData)wellKnownData; // Similar to ValidateAttributeUsageAndDecodeWellKnownAttributes, but doesn't load assembly-level attributes from source // and only decodes 3 specific attributes. WellKnownAttributeData limitedDecodeWellKnownAttributes(ImmutableArray<CSharpAttributeData> attributesFromNetModules, ImmutableArray<string> netModuleNames, QuickAttributes attributeMatches) { Debug.Assert(attributesFromNetModules.Any()); Debug.Assert(netModuleNames.Any()); Debug.Assert(attributesFromNetModules.Length == netModuleNames.Length); int netModuleAttributesCount = attributesFromNetModules.Length; HashSet<CSharpAttributeData> uniqueAttributes = null; CommonAssemblyWellKnownAttributeData result = null; // Attributes from the second added module should override attributes from the first added module, etc. // We don't reach here when the attribute was found in source already. for (int i = netModuleAttributesCount - 1; i >= 0; i--) { CSharpAttributeData attribute = attributesFromNetModules[i]; if (!attribute.HasErrors && ValidateAttributeUsageForNetModuleAttribute(attribute, netModuleNames[i], BindingDiagnosticBag.Discarded, ref uniqueAttributes)) { limitedDecodeWellKnownAttribute(attribute, attributeMatches, ref result); } } WellKnownAttributeData.Seal(result); return result; } // Similar to DecodeWellKnownAttribute but only handles 3 specific attributes and ignores diagnostics. void limitedDecodeWellKnownAttribute(CSharpAttributeData attribute, QuickAttributes attributeMatches, ref CommonAssemblyWellKnownAttributeData result) { if (attributeMatches is QuickAttributes.AssemblySignatureKey && attribute.IsTargetAttribute(this, AttributeDescription.AssemblySignatureKeyAttribute)) { result ??= new CommonAssemblyWellKnownAttributeData(); result.AssemblySignatureKeyAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attributeMatches is QuickAttributes.AssemblyKeyFile && attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyFileAttribute)) { result ??= new CommonAssemblyWellKnownAttributeData(); result.AssemblyKeyFileAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attributeMatches is QuickAttributes.AssemblyKeyName && attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyNameAttribute)) { result ??= new CommonAssemblyWellKnownAttributeData(); result.AssemblyKeyContainerAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } } } private CustomAttributesBag<CSharpAttributeData> GetNetModuleAttributesBag() { if (_lazyNetModuleAttributesBag == null) { LoadAndValidateNetModuleAttributes(ref _lazyNetModuleAttributesBag); } return _lazyNetModuleAttributesBag; } internal CommonAssemblyWellKnownAttributeData GetNetModuleDecodedWellKnownAttributeData() { var attributesBag = this.GetNetModuleAttributesBag(); Debug.Assert(attributesBag.IsSealed); return (CommonAssemblyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } internal ImmutableArray<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { var builder = ArrayBuilder<SyntaxList<AttributeListSyntax>>.GetInstance(); var declarations = DeclaringCompilation.MergedRootDeclaration.Declarations; foreach (RootSingleNamespaceDeclaration rootNs in declarations) { if (rootNs.HasAssemblyAttributes) { var tree = rootNs.Location.SourceTree; var root = (CompilationUnitSyntax)tree.GetRoot(); builder.Add(root.AttributeLists); } } return builder.ToImmutableAndFree(); } private void EnsureAttributesAreBound() { if ((_lazySourceAttributesBag == null || !_lazySourceAttributesBag.IsSealed) && LoadAndValidateAttributes(OneOrMany.Create(GetAttributeDeclarations()), ref _lazySourceAttributesBag)) { _state.NotePartComplete(CompletionPart.Attributes); } } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private CustomAttributesBag<CSharpAttributeData> GetSourceAttributesBag() { EnsureAttributesAreBound(); return _lazySourceAttributesBag; } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> /// <remarks> /// NOTE: This method should always be kept as a sealed override. /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetSourceAttributesBag"/> method. /// </remarks> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { var attributes = this.GetSourceAttributesBag().Attributes; var netmoduleAttributes = this.GetNetModuleAttributesBag().Attributes; Debug.Assert(!attributes.IsDefault); Debug.Assert(!netmoduleAttributes.IsDefault); if (attributes.Length > 0) { if (netmoduleAttributes.Length > 0) { attributes = attributes.Concat(netmoduleAttributes); } } else { attributes = netmoduleAttributes; } Debug.Assert(!attributes.IsDefault); return attributes; } /// <summary> /// Returns true if the assembly attribute at the given index is a duplicate assembly attribute that must not be emitted. /// Duplicate assembly attributes are attributes that bind to the same constructor and have identical arguments. /// </summary> /// <remarks> /// This method must be invoked only after all the assembly attributes have been bound. /// </remarks> internal bool IsIndexOfOmittedAssemblyAttribute(int index) { Debug.Assert(_lazyOmittedAttributeIndices == null || !_lazyOmittedAttributeIndices.Any(i => i < 0 || i >= this.GetAttributes().Length)); Debug.Assert(_lazySourceAttributesBag.IsSealed); Debug.Assert(_lazyNetModuleAttributesBag.IsSealed); Debug.Assert(index >= 0); Debug.Assert(index < this.GetAttributes().Length); return _lazyOmittedAttributeIndices != null && _lazyOmittedAttributeIndices.Contains(index); } /// <summary> /// Returns data decoded from source assembly attributes or null if there are none. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// TODO: We should replace methods GetSourceDecodedWellKnownAttributeData and GetNetModuleDecodedWellKnownAttributeData with /// a single method GetDecodedWellKnownAttributeData, which merges DecodedWellKnownAttributeData from source and netmodule attributes. /// </remarks> internal CommonAssemblyWellKnownAttributeData GetSourceDecodedWellKnownAttributeData() { var attributesBag = _lazySourceAttributesBag; if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetSourceAttributesBag(); } return (CommonAssemblyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } #nullable enable /// <remarks> /// This implements the same logic as <see cref="GetSourceDecodedWellKnownAttributeData()"/> /// but loading a smaller set of attributes if possible, to reduce circularity. /// </remarks> private CommonAssemblyWellKnownAttributeData? GetSourceDecodedWellKnownAttributeData(QuickAttributes attribute) { CustomAttributesBag<CSharpAttributeData>? attributesBag = _lazySourceAttributesBag; if (attributesBag?.IsDecodedWellKnownAttributeDataComputed == true) { return (CommonAssemblyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } attributesBag = null; Func<AttributeSyntax, bool> attributeMatches = attribute switch { QuickAttributes.AssemblySignatureKey => isPossibleAssemblySignatureKeyAttribute, QuickAttributes.AssemblyKeyName => isPossibleAssemblyKeyNameAttribute, QuickAttributes.AssemblyKeyFile => isPossibleAssemblyKeyFileAttribute, _ => throw ExceptionUtilities.UnexpectedValue(attribute) }; LoadAndValidateAttributes(OneOrMany.Create(GetAttributeDeclarations()), ref attributesBag, attributeMatchesOpt: attributeMatches); return (CommonAssemblyWellKnownAttributeData?)attributesBag?.DecodedWellKnownAttributeData; bool isPossibleAssemblySignatureKeyAttribute(AttributeSyntax node) { QuickAttributeChecker checker = this.DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder(node).QuickAttributeChecker; return checker.IsPossibleMatch(node, QuickAttributes.AssemblySignatureKey); } bool isPossibleAssemblyKeyNameAttribute(AttributeSyntax node) { QuickAttributeChecker checker = this.DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder(node).QuickAttributeChecker; return checker.IsPossibleMatch(node, QuickAttributes.AssemblyKeyName); } bool isPossibleAssemblyKeyFileAttribute(AttributeSyntax node) { QuickAttributeChecker checker = this.DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder(node).QuickAttributeChecker; return checker.IsPossibleMatch(node, QuickAttributes.AssemblyKeyFile); } } #nullable disable /// <summary> /// This only forces binding of attributes that look like they may be forwarded types attributes (syntactically). /// </summary> internal HashSet<NamedTypeSymbol> GetForwardedTypes() { CustomAttributesBag<CSharpAttributeData> attributesBag = _lazySourceAttributesBag; if (attributesBag?.IsDecodedWellKnownAttributeDataComputed == true) { // Use already decoded attributes return ((CommonAssemblyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData)?.ForwardedTypes; } attributesBag = null; LoadAndValidateAttributes(OneOrMany.Create(GetAttributeDeclarations()), ref attributesBag, attributeMatchesOpt: this.IsPossibleForwardedTypesAttribute); var wellKnownAttributeData = (CommonAssemblyWellKnownAttributeData)attributesBag?.DecodedWellKnownAttributeData; return wellKnownAttributeData?.ForwardedTypes; } private bool IsPossibleForwardedTypesAttribute(AttributeSyntax node) { QuickAttributeChecker checker = this.DeclaringCompilation.GetBinderFactory(node.SyntaxTree).GetBinder(node).QuickAttributeChecker; return checker.IsPossibleMatch(node, QuickAttributes.TypeForwardedTo); } private static IEnumerable<Cci.SecurityAttribute> GetSecurityAttributes(CustomAttributesBag<CSharpAttributeData> attributesBag) { Debug.Assert(attributesBag.IsSealed); var wellKnownAttributeData = (CommonAssemblyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; if (wellKnownAttributeData != null) { SecurityWellKnownAttributeData securityData = wellKnownAttributeData.SecurityInformation; if (securityData != null) { foreach (var securityAttribute in securityData.GetSecurityAttributes<CSharpAttributeData>(attributesBag.Attributes)) { yield return securityAttribute; } } } } internal IEnumerable<Cci.SecurityAttribute> GetSecurityAttributes() { // user defined security attributes: foreach (var securityAttribute in GetSecurityAttributes(this.GetSourceAttributesBag())) { yield return securityAttribute; } // Net module assembly security attributes: foreach (var securityAttribute in GetSecurityAttributes(this.GetNetModuleAttributesBag())) { yield return securityAttribute; } // synthesized security attributes: if (_compilation.Options.AllowUnsafe) { // NOTE: GlobalAttrBind::EmitCompilerGeneratedAttrs skips attribute if the well-known types aren't available. if (!(_compilation.GetWellKnownType(WellKnownType.System_Security_UnverifiableCodeAttribute) is MissingMetadataTypeSymbol) && !(_compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityPermissionAttribute) is MissingMetadataTypeSymbol)) { var securityActionType = _compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction); if (!(securityActionType is MissingMetadataTypeSymbol)) { var fieldRequestMinimum = (FieldSymbol)_compilation.GetWellKnownTypeMember(WellKnownMember.System_Security_Permissions_SecurityAction__RequestMinimum); // NOTE: Dev10 handles missing enum value. object constantValue = (object)fieldRequestMinimum == null || fieldRequestMinimum.HasUseSiteError ? 0 : fieldRequestMinimum.ConstantValue; var typedConstantRequestMinimum = new TypedConstant(securityActionType, TypedConstantKind.Enum, constantValue); var boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); Debug.Assert(!boolType.HasUseSiteError, "Use site errors should have been checked ahead of time (type bool)."); var typedConstantTrue = new TypedConstant(boolType, TypedConstantKind.Primitive, value: true); var attribute = _compilation.TrySynthesizeAttribute( WellKnownMember.System_Security_Permissions_SecurityPermissionAttribute__ctor, ImmutableArray.Create(typedConstantRequestMinimum), ImmutableArray.Create(new KeyValuePair<WellKnownMember, TypedConstant>( WellKnownMember.System_Security_Permissions_SecurityPermissionAttribute__SkipVerification, typedConstantTrue))); if (attribute != null) { yield return new Cci.SecurityAttribute((DeclarativeSecurityAction)(int)constantValue, attribute); } } } } } internal override ImmutableArray<AssemblySymbol> GetNoPiaResolutionAssemblies() { return _modules[0].GetReferencedAssemblySymbols(); } internal override void SetNoPiaResolutionAssemblies(ImmutableArray<AssemblySymbol> assemblies) { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<AssemblySymbol> GetLinkedReferencedAssemblies() { // SourceAssemblySymbol is never used directly as a reference // when it is or any of its references is linked. return default(ImmutableArray<AssemblySymbol>); } internal override void SetLinkedReferencedAssemblies(ImmutableArray<AssemblySymbol> assemblies) { // SourceAssemblySymbol is never used directly as a reference // when it is or any of its references is linked. throw ExceptionUtilities.Unreachable; } internal override bool IsLinked { get { return false; } } internal bool DeclaresTheObjectClass { get { if ((object)this.CorLibrary != (object)this) { return false; } var obj = GetSpecialType(SpecialType.System_Object); return !obj.IsErrorType() && obj.DeclaredAccessibility == Accessibility.Public; } } public override bool MightContainExtensionMethods { get { // Note this method returns true until all ContainsExtensionMethods is // called, after which the correct value will be returned. In other words, // the return value may change from true to false on subsequent calls. if (_lazyContainsExtensionMethods.HasValue()) { return _lazyContainsExtensionMethods.Value(); } return true; } } private bool HasDebuggableAttribute { get { CommonAssemblyWellKnownAttributeData assemblyData = this.GetSourceDecodedWellKnownAttributeData(); return assemblyData != null && assemblyData.HasDebuggableAttribute; } } private bool HasReferenceAssemblyAttribute { get { CommonAssemblyWellKnownAttributeData assemblyData = this.GetSourceDecodedWellKnownAttributeData(); return assemblyData != null && assemblyData.HasReferenceAssemblyAttribute; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); CSharpCompilationOptions options = _compilation.Options; bool isBuildingNetModule = options.OutputKind.IsNetModule(); bool containsExtensionMethods = this.ContainsExtensionMethods(); if (containsExtensionMethods) { // No need to check if [Extension] attribute was explicitly set since // we'll issue CS1112 error in those cases and won't generate IL. AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor)); } // Synthesize CompilationRelaxationsAttribute only if all the following requirements are met: // (a) We are not building a netmodule. // (b) There is no applied CompilationRelaxationsAttribute assembly attribute in source. // (c) There is no applied CompilationRelaxationsAttribute assembly attribute for any of the added PE modules. // Above requirements also hold for synthesizing RuntimeCompatibilityAttribute attribute. bool emitCompilationRelaxationsAttribute = !isBuildingNetModule && !this.Modules.Any(m => m.HasAssemblyCompilationRelaxationsAttribute); if (emitCompilationRelaxationsAttribute) { // Synthesize attribute: [CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] // NOTE: GlobalAttrBind::EmitCompilerGeneratedAttrs skips attribute if the well-known types aren't available. if (!(_compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute) is MissingMetadataTypeSymbol)) { var int32Type = _compilation.GetSpecialType(SpecialType.System_Int32); Debug.Assert(!int32Type.HasUseSiteError, "Use site errors should have been checked ahead of time (type int)."); var typedConstantNoStringInterning = new TypedConstant(int32Type, TypedConstantKind.Primitive, Cci.Constants.CompilationRelaxations_NoStringInterning); AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32, ImmutableArray.Create(typedConstantNoStringInterning))); } } bool emitRuntimeCompatibilityAttribute = !isBuildingNetModule && !this.Modules.Any(m => m.HasAssemblyRuntimeCompatibilityAttribute); if (emitRuntimeCompatibilityAttribute) { // Synthesize attribute: [RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] // NOTE: GlobalAttrBind::EmitCompilerGeneratedAttrs skips attribute if the well-known types aren't available. if (!(_compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute) is MissingMetadataTypeSymbol)) { var boolType = _compilation.GetSpecialType(SpecialType.System_Boolean); Debug.Assert(!boolType.HasUseSiteError, "Use site errors should have been checked ahead of time (type bool)."); var typedConstantTrue = new TypedConstant(boolType, TypedConstantKind.Primitive, value: true); AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor, ImmutableArray<TypedConstant>.Empty, ImmutableArray.Create(new KeyValuePair<WellKnownMember, TypedConstant>( WellKnownMember.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows, typedConstantTrue)))); } } // Synthesize DebuggableAttribute only if all the following requirements are met: // (a) We are not building a netmodule. // (b) We are emitting debug information (full or pdbonly). // (c) There is no applied DebuggableAttribute assembly attribute in source. // CONSIDER: Native VB compiler and Roslyn VB compiler also have an additional requirement: There is no applied DebuggableAttribute *module* attribute in source. // CONSIDER: Should we check for module DebuggableAttribute? if (!isBuildingNetModule && !this.HasDebuggableAttribute) { AddSynthesizedAttribute(ref attributes, _compilation.SynthesizeDebuggableAttribute()); } if (_compilation.Options.OutputKind == OutputKind.NetModule) { // If the attribute is applied in source, do not add synthetic one. // If its value is different from the supplied through options, an error should have been reported by now. if (!string.IsNullOrEmpty(_compilation.Options.CryptoKeyContainer) && (object)AssemblyKeyContainerAttributeSetting == (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { var stringType = _compilation.GetSpecialType(SpecialType.System_String); Debug.Assert(!stringType.HasUseSiteError, "Use site errors should have been checked ahead of time (type string)."); var typedConstant = new TypedConstant(stringType, TypedConstantKind.Primitive, _compilation.Options.CryptoKeyContainer); AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute(WellKnownMember.System_Reflection_AssemblyKeyNameAttribute__ctor, ImmutableArray.Create(typedConstant))); } if (!String.IsNullOrEmpty(_compilation.Options.CryptoKeyFile) && (object)AssemblyKeyFileAttributeSetting == (object)CommonAssemblyWellKnownAttributeData.StringMissingValue) { var stringType = _compilation.GetSpecialType(SpecialType.System_String); Debug.Assert(!stringType.HasUseSiteError, "Use site errors should have been checked ahead of time (type string)."); var typedConstant = new TypedConstant(stringType, TypedConstantKind.Primitive, _compilation.Options.CryptoKeyFile); AddSynthesizedAttribute(ref attributes, _compilation.TrySynthesizeAttribute(WellKnownMember.System_Reflection_AssemblyKeyFileAttribute__ctor, ImmutableArray.Create(typedConstant))); } } } /// <summary> /// Returns true if and only if at least one type within the assembly contains /// extension methods. Note, this method is expensive since it potentially /// inspects all types within the assembly. The expectation is that this method is /// only called at emit time, when all types have been or will be traversed anyway. /// </summary> private bool ContainsExtensionMethods() { if (!_lazyContainsExtensionMethods.HasValue()) { _lazyContainsExtensionMethods = ContainsExtensionMethods(_modules).ToThreeState(); } return _lazyContainsExtensionMethods.Value(); } private static bool ContainsExtensionMethods(ImmutableArray<ModuleSymbol> modules) { foreach (var module in modules) { if (ContainsExtensionMethods(module.GlobalNamespace)) { return true; } } return false; } private static bool ContainsExtensionMethods(NamespaceSymbol ns) { foreach (var member in ns.GetMembersUnordered()) { switch (member.Kind) { case SymbolKind.Namespace: if (ContainsExtensionMethods((NamespaceSymbol)member)) { return true; } break; case SymbolKind.NamedType: if (((NamedTypeSymbol)member).MightContainExtensionMethods) { return true; } break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } return false; } //Once the computation of the AssemblyIdentity is complete, check whether //any of the IVT access grants that were optimistically made during AssemblyIdentity computation //are in fact invalid now that the full identity is known. private void CheckOptimisticIVTAccessGrants(BindingDiagnosticBag bag) { ConcurrentDictionary<AssemblySymbol, bool> haveGrantedAssemblies = _optimisticallyGrantedInternalsAccess; if (haveGrantedAssemblies != null) { foreach (var otherAssembly in haveGrantedAssemblies.Keys) { IVTConclusion conclusion = MakeFinalIVTDetermination(otherAssembly); Debug.Assert(conclusion != IVTConclusion.NoRelationshipClaimed); if (conclusion == IVTConclusion.PublicKeyDoesntMatch) bag.Add(ErrorCode.ERR_FriendRefNotEqualToThis, NoLocation.Singleton, otherAssembly.Identity, this.Identity); else if (conclusion == IVTConclusion.OneSignedOneNot) bag.Add(ErrorCode.ERR_FriendRefSigningMismatch, NoLocation.Singleton, otherAssembly.Identity); } } } internal override IEnumerable<ImmutableArray<byte>> GetInternalsVisibleToPublicKeys(string simpleName) { //EDMAURER assume that if EnsureAttributesAreBound() returns, then the internals visible to map has been populated. //Do not optimize by checking if m_lazyInternalsVisibleToMap is Nothing. It may be non-null yet still //incomplete because another thread is in the process of building it. EnsureAttributesAreBound(); if (_lazyInternalsVisibleToMap == null) return SpecializedCollections.EmptyEnumerable<ImmutableArray<byte>>(); ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, string>> result = null; _lazyInternalsVisibleToMap.TryGetValue(simpleName, out result); return (result != null) ? result.Keys : SpecializedCollections.EmptyEnumerable<ImmutableArray<byte>>(); } internal override bool AreInternalsVisibleToThisAssembly(AssemblySymbol potentialGiverOfAccess) { // Ensure that optimistic IVT access is only granted to requests that originated on the thread //that is trying to compute the assembly identity. This gives us deterministic behavior when //two threads are checking IVT access but only one of them is in the process of computing identity. //as an optimization confirm that the identity has not yet been computed to avoid testing TLS if (_lazyStrongNameKeys == null) { var assemblyWhoseKeysAreBeingComputed = t_assemblyForWhichCurrentThreadIsComputingKeys; if ((object)assemblyWhoseKeysAreBeingComputed != null) { //ThrowIfFalse(assemblyWhoseKeysAreBeingComputed Is Me); if (!potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(this.Name).IsEmpty()) { if (_optimisticallyGrantedInternalsAccess == null) Interlocked.CompareExchange(ref _optimisticallyGrantedInternalsAccess, new ConcurrentDictionary<AssemblySymbol, bool>(), null); _optimisticallyGrantedInternalsAccess.TryAdd(potentialGiverOfAccess, true); return true; } else return false; } } IVTConclusion conclusion = MakeFinalIVTDetermination(potentialGiverOfAccess); return conclusion == IVTConclusion.Match || conclusion == IVTConclusion.OneSignedOneNot; } private AssemblyIdentity ComputeIdentity() { return new AssemblyIdentity( _assemblySimpleName, VersionHelper.GenerateVersionFromPatternAndCurrentTime(_compilation.Options.CurrentLocalTime, AssemblyVersionAttributeSetting), this.AssemblyCultureAttributeSetting, StrongNameKeys.PublicKey, hasPublicKey: !StrongNameKeys.PublicKey.IsDefault); } //This maps from assembly name to a set of public keys. It uses concurrent dictionaries because it is built, //one attribute at a time, in the callback that validates an attribute's application to a symbol. It is assumed //to be complete after a call to GetAttributes(). The second dictionary is acting like a set. The value element is //only used when the key is empty in which case it stores the location and value of the attribute string which //may be used to construct a diagnostic if the assembly being compiled is found to be strong named. private ConcurrentDictionary<string, ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, string>>> _lazyInternalsVisibleToMap; private static Location GetAssemblyAttributeLocationForDiagnostic(AttributeSyntax attributeSyntaxOpt) { return (object)attributeSyntaxOpt != null ? attributeSyntaxOpt.Location : NoLocation.Singleton; } private void DecodeTypeForwardedToAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { // this code won't be called unless we bound a well-formed, semantically correct ctor call. Debug.Assert(!arguments.Attribute.HasErrors); var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; TypeSymbol forwardedType = (TypeSymbol)arguments.Attribute.CommonConstructorArguments[0].ValueInternal; // This can happen if the argument is the null literal. if ((object)forwardedType == null) { diagnostics.Add(ErrorCode.ERR_InvalidFwdType, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt)); return; } UseSiteInfo<AssemblySymbol> useSiteInfo = forwardedType.GetUseSiteInfo(); if (useSiteInfo.DiagnosticInfo?.Code != (int)ErrorCode.ERR_UnexpectedUnboundGenericName && diagnostics.Add(useSiteInfo, useSiteInfo.DiagnosticInfo is object ? GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt) : Location.None)) { return; } Debug.Assert(forwardedType.TypeKind != TypeKind.Error); if (forwardedType.ContainingAssembly == this) { diagnostics.Add(ErrorCode.ERR_ForwardedTypeInThisAssembly, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt), forwardedType); return; } if ((object)forwardedType.ContainingType != null) { diagnostics.Add(ErrorCode.ERR_ForwardedTypeIsNested, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt), forwardedType, forwardedType.ContainingType); return; } if (forwardedType.Kind != SymbolKind.NamedType) { // NOTE: Dev10 actually tests whether the forwarded type is an aggregate. This would seem to // exclude nullable and void, but that shouldn't be an issue because they have to be defined in // corlib (since they are special types) and corlib can't refer to other assemblies (by definition). diagnostics.Add(ErrorCode.ERR_InvalidFwdType, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt)); return; } // NOTE: There is no danger of the type being forwarded back to this assembly, because the type // won't even bind successfully unless we have a reference to an assembly that actually contains // the type. var assemblyData = arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>(); HashSet<NamedTypeSymbol> forwardedTypes = assemblyData.ForwardedTypes; if (forwardedTypes == null) { forwardedTypes = new HashSet<NamedTypeSymbol>() { (NamedTypeSymbol)forwardedType }; assemblyData.ForwardedTypes = forwardedTypes; } else if (!forwardedTypes.Add((NamedTypeSymbol)forwardedType)) { // NOTE: For the purposes of reporting this error, Dev10 considers C<int> and C<char> // different types. However, it will actually emit a single forwarder for C`1 (i.e. // we'll have to de-dup again at emit time). diagnostics.Add(ErrorCode.ERR_DuplicateTypeForwarder, GetAssemblyAttributeLocationForDiagnostic(arguments.AttributeSyntaxOpt), forwardedType); } } private void DecodeOneInternalsVisibleToAttribute( AttributeSyntax nodeOpt, CSharpAttributeData attrData, BindingDiagnosticBag diagnostics, int index, ref ConcurrentDictionary<string, ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, string>>> lazyInternalsVisibleToMap) { // this code won't be called unless we bound a well-formed, semantically correct ctor call. Debug.Assert(!attrData.HasErrors); string displayName = (string)attrData.CommonConstructorArguments[0].ValueInternal; if (displayName == null) { diagnostics.Add(ErrorCode.ERR_CannotPassNullForFriendAssembly, GetAssemblyAttributeLocationForDiagnostic(nodeOpt)); return; } AssemblyIdentity identity; AssemblyIdentityParts parts; if (!AssemblyIdentity.TryParseDisplayName(displayName, out identity, out parts)) { diagnostics.Add(ErrorCode.WRN_InvalidAssemblyName, GetAssemblyAttributeLocationForDiagnostic(nodeOpt), displayName); AddOmittedAttributeIndex(index); return; } // Allow public key token due to compatibility reasons, but we are not going to use its value. const AssemblyIdentityParts allowedParts = AssemblyIdentityParts.Name | AssemblyIdentityParts.PublicKey | AssemblyIdentityParts.PublicKeyToken; if ((parts & ~allowedParts) != 0) { diagnostics.Add(ErrorCode.ERR_FriendAssemblyBadArgs, GetAssemblyAttributeLocationForDiagnostic(nodeOpt), displayName); return; } if (lazyInternalsVisibleToMap == null) { Interlocked.CompareExchange(ref lazyInternalsVisibleToMap, new ConcurrentDictionary<string, ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, String>>>(StringComparer.OrdinalIgnoreCase), null); } //later, once the identity is established we confirm that if the assembly being //compiled is signed all of the IVT attributes specify a key. Stash the location for that //in the event that a diagnostic needs to be produced. Tuple<Location, string> locationAndValue = null; // only need to store anything when there is no public key. The only reason to store // this stuff is for production of errors when the assembly is signed but the IVT attrib // doesn't contain a public key. if (identity.PublicKey.IsEmpty) { locationAndValue = new Tuple<Location, string>(GetAssemblyAttributeLocationForDiagnostic(nodeOpt), displayName); } //when two threads are attempting to update the internalsVisibleToMap one of these TryAdd() //calls can fail. We assume that the 'other' thread in that case will successfully add the same //contents eventually. ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, string>> keys = null; if (lazyInternalsVisibleToMap.TryGetValue(identity.Name, out keys)) { keys.TryAdd(identity.PublicKey, locationAndValue); } else { keys = new ConcurrentDictionary<ImmutableArray<byte>, Tuple<Location, String>>(); keys.TryAdd(identity.PublicKey, locationAndValue); lazyInternalsVisibleToMap.TryAdd(identity.Name, keys); } } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return this; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.Assembly; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { return IsInteractive ? AttributeLocation.None : AttributeLocation.Assembly | AttributeLocation.Module; } } internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { DecodeWellKnownAttribute(ref arguments, arguments.Index, isFromNetModule: false); } private void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, int index, bool isFromNetModule) { var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); int signature; var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; if (attribute.IsTargetAttribute(this, AttributeDescription.InternalsVisibleToAttribute)) { DecodeOneInternalsVisibleToAttribute(arguments.AttributeSyntaxOpt, attribute, diagnostics, index, ref _lazyInternalsVisibleToMap); } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblySignatureKeyAttribute)) { var signatureKey = (string)attribute.CommonConstructorArguments[0].ValueInternal; arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblySignatureKeyAttributeSetting = signatureKey; if (!StrongNameKeys.IsValidPublicKeyString(signatureKey)) { diagnostics.Add(ErrorCode.ERR_InvalidSignaturePublicKey, attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt)); } } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyFileAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyKeyFileAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyKeyNameAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyKeyContainerAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDelaySignAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyDelaySignAttributeSetting = (bool)attribute.CommonConstructorArguments[0].ValueInternal ? ThreeState.True : ThreeState.False; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyVersionAttribute)) { string verString = (string)attribute.CommonConstructorArguments[0].ValueInternal; Version version; if (!VersionHelper.TryParseAssemblyVersion(verString, allowWildcard: !_compilation.IsEmitDeterministic, version: out version)) { Location attributeArgumentSyntaxLocation = attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt); bool foundBadWildcard = _compilation.IsEmitDeterministic && verString?.Contains('*') == true; diagnostics.Add(foundBadWildcard ? ErrorCode.ERR_InvalidVersionFormatDeterministic : ErrorCode.ERR_InvalidVersionFormat, attributeArgumentSyntaxLocation); } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyVersionAttributeSetting = version; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyFileVersionAttribute)) { Version dummy; string verString = (string)attribute.CommonConstructorArguments[0].ValueInternal; if (!VersionHelper.TryParse(verString, version: out dummy)) { Location attributeArgumentSyntaxLocation = attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt); diagnostics.Add(ErrorCode.WRN_InvalidVersionFormat, attributeArgumentSyntaxLocation); } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyFileVersionAttributeSetting = verString; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTitleAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyTitleAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyDescriptionAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyDescriptionAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCultureAttribute)) { var cultureString = (string)attribute.CommonConstructorArguments[0].ValueInternal; if (!string.IsNullOrEmpty(cultureString)) { if (_compilation.Options.OutputKind.IsApplication()) { diagnostics.Add(ErrorCode.ERR_InvalidAssemblyCultureForExe, attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt)); } else if (!AssemblyIdentity.IsValidCultureName(cultureString)) { diagnostics.Add(ErrorCode.ERR_InvalidAssemblyCulture, attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt)); cultureString = null; } } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyCultureAttributeSetting = cultureString; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCompanyAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyCompanyAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyProductAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyProductAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyInformationalVersionAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyInformationalVersionAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.SatelliteContractVersionAttribute)) { //just check the format of this one, don't do anything else with it. Version dummy; string verString = (string)attribute.CommonConstructorArguments[0].ValueInternal; if (!VersionHelper.TryParseAssemblyVersion(verString, allowWildcard: false, version: out dummy)) { Location attributeArgumentSyntaxLocation = attribute.GetAttributeArgumentSyntaxLocation(0, arguments.AttributeSyntaxOpt); diagnostics.Add(ErrorCode.ERR_InvalidVersionFormat2, attributeArgumentSyntaxLocation); } } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyCopyrightAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyCopyrightAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if (attribute.IsTargetAttribute(this, AttributeDescription.AssemblyTrademarkAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyTrademarkAttributeSetting = (string)attribute.CommonConstructorArguments[0].ValueInternal; } else if ((signature = attribute.GetTargetAttributeSignatureIndex(this, AttributeDescription.AssemblyFlagsAttribute)) != -1) { object value = attribute.CommonConstructorArguments[0].ValueInternal; AssemblyFlags nameFlags; if (signature == 0 || signature == 1) { nameFlags = (AssemblyFlags)(AssemblyNameFlags)value; } else { nameFlags = (AssemblyFlags)(uint)value; } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyFlagsAttributeSetting = nameFlags; } else if (attribute.IsSecurityAttribute(_compilation)) { attribute.DecodeSecurityAttribute<CommonAssemblyWellKnownAttributeData>(this, _compilation, ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.ClassInterfaceAttribute)) { attribute.DecodeClassInterfaceAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.TypeLibVersionAttribute)) { ValidateIntegralAttributeNonNegativeArguments(attribute, arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.ComCompatibleVersionAttribute)) { ValidateIntegralAttributeNonNegativeArguments(attribute, arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.GuidAttribute)) { attribute.DecodeGuidAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.CompilationRelaxationsAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().HasCompilationRelaxationsAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.ReferenceAssemblyAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().HasReferenceAssemblyAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.RuntimeCompatibilityAttribute)) { bool wrapNonExceptionThrows = true; foreach (var namedArg in attribute.CommonNamedArguments) { switch (namedArg.Key) { case "WrapNonExceptionThrows": wrapNonExceptionThrows = namedArg.Value.DecodeValue<bool>(SpecialType.System_Boolean); break; } } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().RuntimeCompatibilityWrapNonExceptionThrows = wrapNonExceptionThrows; } else if (attribute.IsTargetAttribute(this, AttributeDescription.DebuggableAttribute)) { arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().HasDebuggableAttribute = true; } else if (!isFromNetModule && attribute.IsTargetAttribute(this, AttributeDescription.TypeForwardedToAttribute)) { DecodeTypeForwardedToAttribute(ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.CaseSensitiveExtensionAttribute)) { if ((object)arguments.AttributeSyntaxOpt != null) { // [Extension] attribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitExtension, arguments.AttributeSyntaxOpt.Location); } } else if ((signature = attribute.GetTargetAttributeSignatureIndex(this, AttributeDescription.AssemblyAlgorithmIdAttribute)) != -1) { object value = attribute.CommonConstructorArguments[0].ValueInternal; AssemblyHashAlgorithm algorithmId; if (signature == 0) { algorithmId = (AssemblyHashAlgorithm)value; } else { algorithmId = (AssemblyHashAlgorithm)(uint)value; } arguments.GetOrCreateData<CommonAssemblyWellKnownAttributeData>().AssemblyAlgorithmIdAttributeSetting = algorithmId; } } // Checks that the integral arguments for the given well-known attribute are non-negative. private static void ValidateIntegralAttributeNonNegativeArguments(CSharpAttributeData attribute, AttributeSyntax nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!attribute.HasErrors); int argCount = attribute.CommonConstructorArguments.Length; for (int i = 0; i < argCount; i++) { int arg = attribute.GetConstructorArgument<int>(i, SpecialType.System_Int32); if (arg < 0) { // CS0591: Invalid value for argument to '{0}' attribute Location attributeArgumentSyntaxLocation = attribute.GetAttributeArgumentSyntaxLocation(i, nodeOpt); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, (object)nodeOpt != null ? nodeOpt.GetErrorDisplayName() : ""); } } } internal void NoteFieldAccess(FieldSymbol field, bool read, bool write) { var container = field.ContainingType as SourceMemberContainerTypeSymbol; if ((object)container == null) { // field is not in source. return; } container.EnsureFieldDefinitionsNoted(); if (_unusedFieldWarnings.IsDefault) { if (read) { _unreadFields.Remove(field); } if (write) { bool _; _unassignedFieldsMap.TryRemove(field, out _); } } else { // It's acceptable to run flow analysis again after the diagnostics have been computed - just // make sure that the nothing is different than the first time. Debug.Assert( !(read && _unreadFields.Remove(field)), "we are already reporting unused field warnings, there could be no more changes"); Debug.Assert( !(write && _unassignedFieldsMap.ContainsKey(field)), "we are already reporting unused field warnings, there could be no more changes"); } } internal void NoteFieldDefinition(FieldSymbol field, bool isInternal, bool isUnread) { Debug.Assert(_unusedFieldWarnings.IsDefault, "We shouldn't have computed the diagnostics if we're still noting definitions."); _unassignedFieldsMap.TryAdd(field, isInternal); if (isUnread) { _unreadFields.Add(field); } } internal override bool IsNetModule() => this._compilation.Options.OutputKind.IsNetModule(); /// <summary> /// Get the warnings for unused fields. This should only be fetched when all method bodies have been compiled. /// </summary> internal ImmutableArray<Diagnostic> GetUnusedFieldWarnings(CancellationToken cancellationToken) { if (_unusedFieldWarnings.IsDefault) { //Our maps of unread and unassigned fields won't be done until the assembly is complete. this.ForceComplete(locationOpt: null, cancellationToken: cancellationToken); Debug.Assert(this.HasComplete(CompletionPart.Module), "Don't consume unused field information if there are still types to be processed."); // Build this up in a local before we assign it to this.unusedFieldWarnings (so other threads // can see that it's not done). DiagnosticBag diagnostics = DiagnosticBag.GetInstance(); // NOTE: two threads can come in here at the same time. If they do, then they will // share the diagnostic bag. That's alright, as long as each one processes only // the fields that it successfully removes from the shared map/set. Furthermore, // there should be no problem with re-calling this method on the same assembly, // since there will be nothing left in the map/set the second time. bool internalsAreVisible = this.InternalsAreVisible || this.IsNetModule(); HashSet<FieldSymbol> handledUnreadFields = null; foreach (FieldSymbol field in _unassignedFieldsMap.Keys) // Not mutating, so no snapshot required. { bool isInternalAccessibility; bool success = _unassignedFieldsMap.TryGetValue(field, out isInternalAccessibility); Debug.Assert(success, "Once CompletionPart.Module is set, no-one should be modifying the map."); if (isInternalAccessibility && internalsAreVisible) { continue; } if (!field.CanBeReferencedByName) { continue; } var containingType = field.ContainingType as SourceNamedTypeSymbol; if ((object)containingType == null) { continue; } if (field is TupleErrorFieldSymbol) { continue; } bool unread = _unreadFields.Contains(field); if (unread) { if (handledUnreadFields == null) { handledUnreadFields = new HashSet<FieldSymbol>(); } handledUnreadFields.Add(field); } if (containingType.HasStructLayoutAttribute) { continue; } Symbol associatedPropertyOrEvent = field.AssociatedSymbol; if ((object)associatedPropertyOrEvent != null && associatedPropertyOrEvent.Kind == SymbolKind.Event) { if (unread) { diagnostics.Add(ErrorCode.WRN_UnreferencedEvent, associatedPropertyOrEvent.Locations.FirstOrNone(), associatedPropertyOrEvent); } } else if (unread) { diagnostics.Add(ErrorCode.WRN_UnreferencedField, field.Locations.FirstOrNone(), field); } else { diagnostics.Add(ErrorCode.WRN_UnassignedInternalField, field.Locations.FirstOrNone(), field, DefaultValue(field.Type)); } } foreach (FieldSymbol field in _unreadFields) // Not mutating, so no snapshot required. { if (handledUnreadFields != null && handledUnreadFields.Contains(field)) { // Handled in the first foreach loop. continue; } if (!field.CanBeReferencedByName) { continue; } var containingType = field.ContainingType as SourceNamedTypeSymbol; if ((object)containingType != null && !containingType.HasStructLayoutAttribute) { diagnostics.Add(ErrorCode.WRN_UnreferencedFieldAssg, field.Locations.FirstOrNone(), field); } } ImmutableInterlocked.InterlockedInitialize(ref _unusedFieldWarnings, diagnostics.ToReadOnlyAndFree()); } Debug.Assert(!_unusedFieldWarnings.IsDefault); return _unusedFieldWarnings; } private static string DefaultValue(TypeSymbol type) { // TODO: localize these strings if (type.IsReferenceType) return "null"; switch (type.SpecialType) { case SpecialType.System_Boolean: return "false"; case SpecialType.System_Byte: case SpecialType.System_Decimal: case SpecialType.System_Double: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_SByte: case SpecialType.System_Single: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: return "0"; default: return ""; } } internal override NamedTypeSymbol TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies) { int forcedArity = emittedName.ForcedArity; if (emittedName.UseCLSCompliantNameArityEncoding) { if (forcedArity == -1) { forcedArity = emittedName.InferredArity; } else if (forcedArity != emittedName.InferredArity) { return null; } Debug.Assert(forcedArity == emittedName.InferredArity); } if (_lazyForwardedTypesFromSource == null) { IDictionary<string, NamedTypeSymbol> forwardedTypesFromSource; // Get the TypeForwardedTo attributes with minimal binding to avoid cycle problems HashSet<NamedTypeSymbol> forwardedTypes = GetForwardedTypes(); if (forwardedTypes != null) { forwardedTypesFromSource = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance); foreach (NamedTypeSymbol forwardedType in forwardedTypes) { NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition; Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?"); string fullEmittedName = MetadataHelpers.BuildQualifiedName(originalDefinition.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), originalDefinition.MetadataName); // Since we need to allow multiple constructions of the same generic type at the source // level, we need to de-dup the original definitions. forwardedTypesFromSource[fullEmittedName] = originalDefinition; } } else { forwardedTypesFromSource = SpecializedCollections.EmptyDictionary<string, NamedTypeSymbol>(); } _lazyForwardedTypesFromSource = forwardedTypesFromSource; } NamedTypeSymbol result; if (_lazyForwardedTypesFromSource.TryGetValue(emittedName.FullName, out result)) { if ((forcedArity == -1 || result.Arity == forcedArity) && (!emittedName.UseCLSCompliantNameArityEncoding || result.Arity == 0 || result.MangleName)) { return result; } } else if (!_compilation.Options.OutputKind.IsNetModule()) { // See if any of added modules forward the type. // Similar to attributes, type forwarders from the second added module should override type forwarders from the first added module, etc. for (int i = _modules.Length - 1; i > 0; i--) { var peModuleSymbol = (Metadata.PE.PEModuleSymbol)_modules[i]; (AssemblySymbol firstSymbol, AssemblySymbol secondSymbol) = peModuleSymbol.GetAssembliesForForwardedType(ref emittedName); if ((object)firstSymbol != null) { if ((object)secondSymbol != null) { return CreateMultipleForwardingErrorTypeSymbol(ref emittedName, peModuleSymbol, firstSymbol, secondSymbol); } // Don't bother to check the forwarded-to assembly if we've already seen it. if (visitedAssemblies != null && visitedAssemblies.Contains(firstSymbol)) { return CreateCycleInTypeForwarderErrorTypeSymbol(ref emittedName); } else { visitedAssemblies = new ConsList<AssemblySymbol>(this, visitedAssemblies ?? ConsList<AssemblySymbol>.Empty); return firstSymbol.LookupTopLevelMetadataTypeWithCycleDetection(ref emittedName, visitedAssemblies, digThroughForwardedTypes: true); } } } } return null; } internal override IEnumerable<NamedTypeSymbol> GetAllTopLevelForwardedTypes() { return PEModuleBuilder.GetForwardedTypes(this, builder: null); } public override AssemblyMetadata GetMetadata() => null; protected override ISymbol CreateISymbol() { return new PublicModel.SourceAssemblySymbol(this); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Test/Emit/Emit/EmitErrorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// this place is dedicated to emit/codegen related error tests /// </summary> public class EmitErrorTests : EmitMetadataTestBase { #region "Mixed Error Tests" [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadConstantInOtherAssemblyUsedByField() { string source1 = @" public class A { public const int x = x; } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (4,22): error CS0110: The evaluation of the constant value for 'A.x' involves a circular definition Diagnostic(CSharp.ErrorCode.ERR_CircConstValue, "x").WithArguments("A.x")); string source2 = @" public class B { public const int y = A.x; public static void Main() { System.Console.WriteLine(""Hello""); } } "; VerifyEmitDiagnostics(source2, compilation1); } [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadConstantInOtherAssemblyUsedByLocal() { string source1 = @" public class A { public const int x = x; } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (4,22): error CS0110: The evaluation of the constant value for 'A.x' involves a circular definition Diagnostic(CSharp.ErrorCode.ERR_CircConstValue, "x").WithArguments("A.x")); string source2 = @" public class B { public static void Main() { const int y = A.x; System.Console.WriteLine(""Hello""); } } "; VerifyEmitDiagnostics(source2, compilation1, // (6,19): warning CS0219: The variable 'y' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y")); } [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadDefaultArgumentInOtherAssembly() { string source1 = @" public class A { public const int x = x; public static int Goo(int y = x) { return y; } } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (4,22): error CS0110: The evaluation of the constant value for 'A.x' involves a circular definition Diagnostic(CSharp.ErrorCode.ERR_CircConstValue, "x").WithArguments("A.x")); string source2 = @" public class B { public static void Main() { System.Console.WriteLine(A.Goo()); } } "; var compilation2 = CompileAndVerify( source2, new[] { new CSharpCompilationReference(compilation1) }, verify: Verification.Fails); } [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadDefaultArgumentInOtherAssembly_Decimal() { string source1 = @" public class A { public const decimal x = x; public static decimal Goo(decimal y = x) { return y; } } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (4,22): error CS0110: The evaluation of the constant value for 'A.x' involves a circular definition Diagnostic(ErrorCode.ERR_CircConstValue, "x").WithArguments("A.x")); string source2 = @" public class B { public static void Main() { System.Console.WriteLine(A.Goo()); } } "; var compilation2 = CompileAndVerify( source2, new[] { new CSharpCompilationReference(compilation1) }, verify: Verification.Fails); } [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadDefaultArgumentInOtherAssembly_UserDefinedType() { string source1 = @" public struct S { public override string ToString() { return ""S::ToString""; } } public class A { public static S Goo(S p = 42) { return p; } } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (9,27): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'S' // public static S Goo(S p = 42) { return p; } Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "p").WithArguments("int", "S").WithLocation(9, 27)); string source2 = @" public class B { public static void Main() { System.Console.WriteLine(A.Goo()); } } "; var compilation2 = CompileAndVerify( source2, new[] { new CSharpCompilationReference(compilation1) }, verify: Verification.Fails); compilation2.VerifyIL("B.Main()", @" { // Code size 25 (0x19) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: call ""S A.Goo(S)"" IL_000e: box ""S"" IL_0013: call ""void System.Console.WriteLine(object)"" IL_0018: ret }"); } [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadReturnTypeInOtherAssembly() { string source1 = @" public class A { public static Missing Goo() { return null; } } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (4,19): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing")); string source2 = @" public class B { public static void Main() { var f = A.Goo(); System.Console.WriteLine(f); } } "; VerifyEmitDiagnostics(source2, compilation1); } private static void VerifyEmitDiagnostics(string source2, CSharpCompilation compilation1, params DiagnosticDescription[] expectedDiagnostics) { var compilation2 = CreateCompilation(source2, new MetadataReference[] { new CSharpCompilationReference(compilation1) }); compilation2.VerifyDiagnostics(expectedDiagnostics); using (var executableStream = new MemoryStream()) { var result = compilation2.Emit(executableStream); Assert.False(result.Success); result.Diagnostics.Verify(expectedDiagnostics.Concat(new[] { // error CS7038: Failed to emit module 'Test': Unable to determine specific cause of the failure. Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments(compilation2.AssemblyName, "Unable to determine specific cause of the failure.") }).ToArray()); } using (var executableStream = new MemoryStream()) { var result = compilation2.Emit(executableStream, options: new EmitOptions(metadataOnly: true)); Assert.True(result.Success); result.Diagnostics.Verify(); } } [Fact, WorkItem(530211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530211")] public void ModuleNameMismatch() { var moduleSource = "class Test {}"; var netModule = CreateCompilation(moduleSource, options: TestOptions.ReleaseModule, assemblyName: "ModuleNameMismatch"); var moduleMetadata = ModuleMetadata.CreateFromImage(netModule.EmitToArray()); var source = @"class Module1 { }"; var compilationOK = CreateCompilation(source, new MetadataReference[] { moduleMetadata.GetReference(filePath: @"R:\A\B\ModuleNameMismatch.netmodule") }); CompileAndVerify(compilationOK); var compilationError = CreateCompilation(source, new MetadataReference[] { moduleMetadata.GetReference(filePath: @"R:\A\B\ModuleNameMismatch.mod") }); compilationError.VerifyDiagnostics( // error CS7086: Module name 'ModuleNameMismatch.netmodule' stored in 'ModuleNameMismatch.mod' must match its filename. Diagnostic(ErrorCode.ERR_NetModuleNameMismatch).WithArguments("ModuleNameMismatch.netmodule", "ModuleNameMismatch.mod")); } [ConditionalFact(typeof(NoIOperationValidation))] public void CS0204_ERR_TooManyLocals() { var builder = new System.Text.StringBuilder(); builder.Append(@" public class A { public static int Main () { "); for (int i = 0; i < 65536; i++) { builder.AppendLine(string.Format(" int i{0} = {0};", i)); } builder.Append(@" return 1; } } "); //Compiling this with optimizations enabled causes the stack scheduler to eliminate a bunch of these locals. //It could eliminate 'em all, but doesn't. var warnOpts = new System.Collections.Generic.Dictionary<string, ReportDiagnostic>(); warnOpts.Add(MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_UnreferencedVarAssg), ReportDiagnostic.Suppress); var compilation1 = CreateCompilation(builder.ToString(), null, TestOptions.DebugDll.WithSpecificDiagnosticOptions(warnOpts)); compilation1.VerifyEmitDiagnostics( // (4,23): error CS0204: Only 65534 locals, including those generated by the compiler, are allowed // public static int Main () Diagnostic(ErrorCode.ERR_TooManyLocals, "Main")); } [Fact, WorkItem(8287, "https://github.com/dotnet/roslyn/issues/8287")] public void ToManyUserStrings() { var builder = new System.Text.StringBuilder(); builder.Append(@" public class A { public static void Main () { "); for (int i = 0; i < 11; i++) { builder.Append("System.Console.WriteLine(\""); builder.Append((char)('A' + i), 1000000); builder.Append("\");"); builder.AppendLine(); } builder.Append(@" } } "); var compilation = CreateCompilation(builder.ToString()); compilation.VerifyEmitDiagnostics( // error CS8103: Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string literals. Diagnostic(ErrorCode.ERR_TooManyUserStrings).WithLocation(1, 1) ); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// this place is dedicated to emit/codegen related error tests /// </summary> public class EmitErrorTests : EmitMetadataTestBase { #region "Mixed Error Tests" [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadConstantInOtherAssemblyUsedByField() { string source1 = @" public class A { public const int x = x; } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (4,22): error CS0110: The evaluation of the constant value for 'A.x' involves a circular definition Diagnostic(CSharp.ErrorCode.ERR_CircConstValue, "x").WithArguments("A.x")); string source2 = @" public class B { public const int y = A.x; public static void Main() { System.Console.WriteLine(""Hello""); } } "; VerifyEmitDiagnostics(source2, compilation1); } [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadConstantInOtherAssemblyUsedByLocal() { string source1 = @" public class A { public const int x = x; } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (4,22): error CS0110: The evaluation of the constant value for 'A.x' involves a circular definition Diagnostic(CSharp.ErrorCode.ERR_CircConstValue, "x").WithArguments("A.x")); string source2 = @" public class B { public static void Main() { const int y = A.x; System.Console.WriteLine(""Hello""); } } "; VerifyEmitDiagnostics(source2, compilation1, // (6,19): warning CS0219: The variable 'y' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y")); } [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadDefaultArgumentInOtherAssembly() { string source1 = @" public class A { public const int x = x; public static int Goo(int y = x) { return y; } } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (4,22): error CS0110: The evaluation of the constant value for 'A.x' involves a circular definition Diagnostic(CSharp.ErrorCode.ERR_CircConstValue, "x").WithArguments("A.x")); string source2 = @" public class B { public static void Main() { System.Console.WriteLine(A.Goo()); } } "; var compilation2 = CompileAndVerify( source2, new[] { new CSharpCompilationReference(compilation1) }, verify: Verification.Fails); } [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadDefaultArgumentInOtherAssembly_Decimal() { string source1 = @" public class A { public const decimal x = x; public static decimal Goo(decimal y = x) { return y; } } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (4,22): error CS0110: The evaluation of the constant value for 'A.x' involves a circular definition Diagnostic(ErrorCode.ERR_CircConstValue, "x").WithArguments("A.x")); string source2 = @" public class B { public static void Main() { System.Console.WriteLine(A.Goo()); } } "; var compilation2 = CompileAndVerify( source2, new[] { new CSharpCompilationReference(compilation1) }, verify: Verification.Fails); } [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadDefaultArgumentInOtherAssembly_UserDefinedType() { string source1 = @" public struct S { public override string ToString() { return ""S::ToString""; } } public class A { public static S Goo(S p = 42) { return p; } } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (9,27): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'S' // public static S Goo(S p = 42) { return p; } Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "p").WithArguments("int", "S").WithLocation(9, 27)); string source2 = @" public class B { public static void Main() { System.Console.WriteLine(A.Goo()); } } "; var compilation2 = CompileAndVerify( source2, new[] { new CSharpCompilationReference(compilation1) }, verify: Verification.Fails); compilation2.VerifyIL("B.Main()", @" { // Code size 25 (0x19) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: call ""S A.Goo(S)"" IL_000e: box ""S"" IL_0013: call ""void System.Console.WriteLine(object)"" IL_0018: ret }"); } [WorkItem(543039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543039")] [Fact] public void BadReturnTypeInOtherAssembly() { string source1 = @" public class A { public static Missing Goo() { return null; } } "; var compilation1 = CreateCompilation(source1); compilation1.VerifyDiagnostics( // (4,19): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing")); string source2 = @" public class B { public static void Main() { var f = A.Goo(); System.Console.WriteLine(f); } } "; VerifyEmitDiagnostics(source2, compilation1); } private static void VerifyEmitDiagnostics(string source2, CSharpCompilation compilation1, params DiagnosticDescription[] expectedDiagnostics) { var compilation2 = CreateCompilation(source2, new MetadataReference[] { new CSharpCompilationReference(compilation1) }); compilation2.VerifyDiagnostics(expectedDiagnostics); using (var executableStream = new MemoryStream()) { var result = compilation2.Emit(executableStream); Assert.False(result.Success); result.Diagnostics.Verify(expectedDiagnostics.Concat(new[] { // error CS7038: Failed to emit module 'Test': Unable to determine specific cause of the failure. Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments(compilation2.AssemblyName, "Unable to determine specific cause of the failure.") }).ToArray()); } using (var executableStream = new MemoryStream()) { var result = compilation2.Emit(executableStream, options: new EmitOptions(metadataOnly: true)); Assert.True(result.Success); result.Diagnostics.Verify(); } } [Fact, WorkItem(530211, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530211")] public void ModuleNameMismatch() { var moduleSource = "class Test {}"; var netModule = CreateCompilation(moduleSource, options: TestOptions.ReleaseModule, assemblyName: "ModuleNameMismatch"); var moduleMetadata = ModuleMetadata.CreateFromImage(netModule.EmitToArray()); var source = @"class Module1 { }"; var compilationOK = CreateCompilation(source, new MetadataReference[] { moduleMetadata.GetReference(filePath: @"R:\A\B\ModuleNameMismatch.netmodule") }); CompileAndVerify(compilationOK); var compilationError = CreateCompilation(source, new MetadataReference[] { moduleMetadata.GetReference(filePath: @"R:\A\B\ModuleNameMismatch.mod") }); compilationError.VerifyDiagnostics( // error CS7086: Module name 'ModuleNameMismatch.netmodule' stored in 'ModuleNameMismatch.mod' must match its filename. Diagnostic(ErrorCode.ERR_NetModuleNameMismatch).WithArguments("ModuleNameMismatch.netmodule", "ModuleNameMismatch.mod")); } [ConditionalFact(typeof(NoIOperationValidation))] public void CS0204_ERR_TooManyLocals() { var builder = new System.Text.StringBuilder(); builder.Append(@" public class A { public static int Main () { "); for (int i = 0; i < 65536; i++) { builder.AppendLine(string.Format(" int i{0} = {0};", i)); } builder.Append(@" return 1; } } "); //Compiling this with optimizations enabled causes the stack scheduler to eliminate a bunch of these locals. //It could eliminate 'em all, but doesn't. var warnOpts = new System.Collections.Generic.Dictionary<string, ReportDiagnostic>(); warnOpts.Add(MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_UnreferencedVarAssg), ReportDiagnostic.Suppress); var compilation1 = CreateCompilation(builder.ToString(), null, TestOptions.DebugDll.WithSpecificDiagnosticOptions(warnOpts)); compilation1.VerifyEmitDiagnostics( // (4,23): error CS0204: Only 65534 locals, including those generated by the compiler, are allowed // public static int Main () Diagnostic(ErrorCode.ERR_TooManyLocals, "Main")); } [Fact, WorkItem(8287, "https://github.com/dotnet/roslyn/issues/8287")] public void ToManyUserStrings() { var builder = new System.Text.StringBuilder(); builder.Append(@" public class A { public static void Main () { "); for (int i = 0; i < 11; i++) { builder.Append("System.Console.WriteLine(\""); builder.Append((char)('A' + i), 1000000); builder.Append("\");"); builder.AppendLine(); } builder.Append(@" } } "); var compilation = CreateCompilation(builder.ToString()); compilation.VerifyEmitDiagnostics( // error CS8103: Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string literals. Diagnostic(ErrorCode.ERR_TooManyUserStrings).WithLocation(1, 1) ); } #endregion } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource_ReferenceCounting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal partial class AbstractAsynchronousTaggerProvider<TTag> { private partial class TagSource { /// <summary>How many taggers are currently using us.</summary> private int _taggers = 0; ~TagSource() { if (!Environment.HasShutdownStarted) { #if DEBUG Contract.Fail($@"Should have been disposed! DataSource-StackTrace: {_dataSource.StackTrace} StackTrace: {_stackTrace}"); #else Contract.Fail($@"Should have been disposed! Try running in Debug to get the allocation callstack"); #endif } } internal void OnTaggerAdded(Tagger _) { // this should be only called from UI thread. // in unit test, must be called from same thread as OnTaggerDisposed Contract.ThrowIfFalse(_taggers >= 0); _taggers++; DebugRecordCurrentThread(); } internal void OnTaggerDisposed(Tagger _) { // this should be only called from UI thread. // in unit test, must be called from same thread as OnTaggerAdded Contract.ThrowIfFalse(_taggers > 0); _taggers--; if (_taggers == 0) { this.Dispose(); DebugVerifyThread(); } } internal void TestOnly_Dispose() => Dispose(); #if DEBUG private Thread? _thread; private string? _stackTrace; private void DebugRecordInitialStackTrace() => _stackTrace = new StackTrace().ToString(); private void DebugRecordCurrentThread() { if (_taggers != 1) { return; } _thread = Thread.CurrentThread; } private void DebugVerifyThread() => Contract.ThrowIfFalse(Thread.CurrentThread == _thread); #else private static void DebugRecordInitialStackTrace() { } private static void DebugRecordCurrentThread() { } private static void DebugVerifyThread() { } #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal partial class AbstractAsynchronousTaggerProvider<TTag> { private partial class TagSource { /// <summary>How many taggers are currently using us.</summary> private int _taggers = 0; ~TagSource() { if (!Environment.HasShutdownStarted) { #if DEBUG Contract.Fail($@"Should have been disposed! DataSource-StackTrace: {_dataSource.StackTrace} StackTrace: {_stackTrace}"); #else Contract.Fail($@"Should have been disposed! Try running in Debug to get the allocation callstack"); #endif } } internal void OnTaggerAdded(Tagger _) { // this should be only called from UI thread. // in unit test, must be called from same thread as OnTaggerDisposed Contract.ThrowIfFalse(_taggers >= 0); _taggers++; DebugRecordCurrentThread(); } internal void OnTaggerDisposed(Tagger _) { // this should be only called from UI thread. // in unit test, must be called from same thread as OnTaggerAdded Contract.ThrowIfFalse(_taggers > 0); _taggers--; if (_taggers == 0) { this.Dispose(); DebugVerifyThread(); } } internal void TestOnly_Dispose() => Dispose(); #if DEBUG private Thread? _thread; private string? _stackTrace; private void DebugRecordInitialStackTrace() => _stackTrace = new StackTrace().ToString(); private void DebugRecordCurrentThread() { if (_taggers != 1) { return; } _thread = Thread.CurrentThread; } private void DebugVerifyThread() => Contract.ThrowIfFalse(Thread.CurrentThread == _thread); #else private static void DebugRecordInitialStackTrace() { } private static void DebugRecordCurrentThread() { } private static void DebugVerifyThread() { } #endif } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/Core/Portable/Completion/Providers/Scripting/GlobalAssemblyCacheCompletionHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal sealed class GlobalAssemblyCacheCompletionHelper { private static readonly Lazy<List<string>> s_lazyAssemblySimpleNames = new(() => GlobalAssemblyCache.Instance.GetAssemblySimpleNames().ToList()); private readonly CompletionItemRules _itemRules; public GlobalAssemblyCacheCompletionHelper(CompletionItemRules itemRules) { Debug.Assert(itemRules != null); _itemRules = itemRules; } public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken) => Task.Run(() => GetItems(directoryPath, cancellationToken)); // internal for testing internal ImmutableArray<CompletionItem> GetItems(string directoryPath, CancellationToken cancellationToken) { using var resultDisposer = ArrayBuilder<CompletionItem>.GetInstance(out var result); var comma = directoryPath.IndexOf(','); if (comma >= 0) { var partialName = directoryPath.Substring(0, comma); foreach (var identity in GetAssemblyIdentities(partialName)) { result.Add(CommonCompletionItem.Create( identity.GetDisplayName(), displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } else { foreach (var displayName in s_lazyAssemblySimpleNames.Value) { cancellationToken.ThrowIfCancellationRequested(); result.Add(CommonCompletionItem.Create( displayName, displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } return result.ToImmutable(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName) { return IOUtilities.PerformIO(() => GlobalAssemblyCache.Instance.GetAssemblyIdentities(partialName), SpecializedCollections.EmptyEnumerable<AssemblyIdentity>()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal sealed class GlobalAssemblyCacheCompletionHelper { private static readonly Lazy<List<string>> s_lazyAssemblySimpleNames = new(() => GlobalAssemblyCache.Instance.GetAssemblySimpleNames().ToList()); private readonly CompletionItemRules _itemRules; public GlobalAssemblyCacheCompletionHelper(CompletionItemRules itemRules) { Debug.Assert(itemRules != null); _itemRules = itemRules; } public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken) => Task.Run(() => GetItems(directoryPath, cancellationToken)); // internal for testing internal ImmutableArray<CompletionItem> GetItems(string directoryPath, CancellationToken cancellationToken) { using var resultDisposer = ArrayBuilder<CompletionItem>.GetInstance(out var result); var comma = directoryPath.IndexOf(','); if (comma >= 0) { var partialName = directoryPath.Substring(0, comma); foreach (var identity in GetAssemblyIdentities(partialName)) { result.Add(CommonCompletionItem.Create( identity.GetDisplayName(), displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } else { foreach (var displayName in s_lazyAssemblySimpleNames.Value) { cancellationToken.ThrowIfCancellationRequested(); result.Add(CommonCompletionItem.Create( displayName, displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } return result.ToImmutable(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName) { return IOUtilities.PerformIO(() => GlobalAssemblyCache.Instance.GetAssemblyIdentities(partialName), SpecializedCollections.EmptyEnumerable<AssemblyIdentity>()); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseIndexOperatorDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { using static Helpers; /// <summary> /// <para>Analyzer that looks for code like:</para> /// /// <list type="number"> /// <item><description><c>s[s.Length - n]</c> and offers to change that to <c>s[^n]</c></description></item> /// <item><description></description><c>s.Get(s.Length - n)</c> and offers to change that to <c>s.Get(^n)</c></item> /// </list> /// /// <para>In order to do convert between indexers, the type must look 'indexable'. Meaning, it must /// have an <see cref="int"/>-returning property called <c>Length</c> or <c>Count</c>, and it must have both an /// <see cref="int"/>-indexer, and a <see cref="T:System.Index"/>-indexer. In order to convert between methods, the type /// must have identical overloads except that one takes an <see cref="int"/>, and the other a <see cref="T:System.Index"/>.</para> /// /// <para>It is assumed that if the type follows this shape that it is well behaved and that this /// transformation will preserve semantics. If this assumption is not good in practice, we /// could always limit the feature to only work on an allow list of known safe types.</para> /// /// <para>Note that this feature only works if the code literally has <c>expr1.Length - expr2</c>. If /// code has this, and is calling into a method that takes either an <see cref="int"/> or a <see cref="T:System.Index"/>, /// it feels very safe to assume this is well behaved and switching to <c>^expr2</c> is going to /// preserve semantics.</para> /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Required to avoid ambiguous reference warnings.")] internal partial class CSharpUseIndexOperatorDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpUseIndexOperatorDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseIndexOperatorDiagnosticId, EnforceOnBuildValues.UseIndexOperator, CSharpCodeStyleOptions.PreferIndexOperator, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_index_operator), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Indexing_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(startContext => { // We're going to be checking every property-reference and invocation in the // compilation. Cache information we compute in this object so we don't have to // continually recompute it. var compilation = startContext.Compilation; var infoCache = new InfoCache(compilation); // The System.Index type is always required to offer this fix. if (infoCache.IndexType == null) { return; } // Register to hear property references, so we can hear about calls to indexers // like: s[s.Length - n] context.RegisterOperationAction( c => AnalyzePropertyReference(c, infoCache), OperationKind.PropertyReference); // Register to hear about methods for: s.Get(s.Length - n) context.RegisterOperationAction( c => AnalyzeInvocation(c, infoCache), OperationKind.Invocation); var arrayType = compilation.GetSpecialType(SpecialType.System_Array); var arrayLengthProperty = TryGetNoArgInt32Property(arrayType, nameof(Array.Length)); if (arrayLengthProperty != null) { // Array indexing is represented with a different operation kind. Register // specifically for that. context.RegisterOperationAction( c => AnalyzeArrayElementReference(c, infoCache, arrayLengthProperty), OperationKind.ArrayElementReference); } }); } private void AnalyzeInvocation( OperationAnalysisContext context, InfoCache infoCache) { var cancellationToken = context.CancellationToken; var invocationOperation = (IInvocationOperation)context.Operation; if (invocationOperation.Arguments.Length != 1) { return; } AnalyzeInvokedMember( context, infoCache, invocationOperation.Instance, invocationOperation.TargetMethod, invocationOperation.Arguments[0].Value, lengthLikePropertyOpt: null, cancellationToken); } private void AnalyzePropertyReference( OperationAnalysisContext context, InfoCache infoCache) { var cancellationToken = context.CancellationToken; var propertyReference = (IPropertyReferenceOperation)context.Operation; // Only analyze indexer calls. if (!propertyReference.Property.IsIndexer) { return; } if (propertyReference.Arguments.Length != 1) { return; } AnalyzeInvokedMember( context, infoCache, propertyReference.Instance, propertyReference.Property.GetMethod, propertyReference.Arguments[0].Value, lengthLikePropertyOpt: null, cancellationToken); } private void AnalyzeArrayElementReference( OperationAnalysisContext context, InfoCache infoCache, IPropertySymbol arrayLengthProperty) { var cancellationToken = context.CancellationToken; var arrayElementReference = (IArrayElementReferenceOperation)context.Operation; // Has to be a single-dimensional element access. if (arrayElementReference.Indices.Length != 1) { return; } AnalyzeInvokedMember( context, infoCache, arrayElementReference.ArrayReference, targetMethodOpt: null, arrayElementReference.Indices[0], lengthLikePropertyOpt: arrayLengthProperty, cancellationToken); } private void AnalyzeInvokedMember( OperationAnalysisContext context, InfoCache infoCache, IOperation instance, IMethodSymbol targetMethodOpt, IOperation argumentValue, IPropertySymbol lengthLikePropertyOpt, CancellationToken cancellationToken) { // look for `s[s.Length - value]` or `s.Get(s.Length- value)`. // Needs to have the one arg for `s.Length - value`, and that arg needs to be // a subtraction. if (instance is null || !IsSubtraction(argumentValue, out var subtraction)) { return; } if (!(subtraction.Syntax is BinaryExpressionSyntax binaryExpression)) { return; } // Only supported on C# 8 and above. var syntaxTree = binaryExpression.SyntaxTree; var parseOptions = (CSharpParseOptions)syntaxTree.Options; if (parseOptions.LanguageVersion < LanguageVersion.CSharp8) { return; } // Don't bother analyzing if the user doesn't like using Index/Range operators. var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferIndexOperator, syntaxTree, cancellationToken); if (!option.Value) { return; } // Ok, looks promising. We're indexing in with some subtraction expression. Examine the // type this indexer is in to see if there's another member that takes a System.Index // that we can convert to. // // Also ensure that the left side of the subtraction : `s.Length - value` is actually // getting the length off the same instance we're indexing into. lengthLikePropertyOpt ??= TryGetLengthLikeProperty(infoCache, targetMethodOpt); if (lengthLikePropertyOpt == null || !IsInstanceLengthCheck(lengthLikePropertyOpt, instance, subtraction.LeftOperand)) { return; } // Everything looks good. We can update this to use the System.Index member instead. context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, binaryExpression.GetLocation(), option.Notification.Severity, ImmutableArray<Location>.Empty, ImmutableDictionary<string, string>.Empty)); } private static IPropertySymbol TryGetLengthLikeProperty(InfoCache infoCache, IMethodSymbol targetMethodOpt) => targetMethodOpt != null && infoCache.TryGetMemberInfo(targetMethodOpt, out var memberInfo) ? memberInfo.LengthLikeProperty : null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { using static Helpers; /// <summary> /// <para>Analyzer that looks for code like:</para> /// /// <list type="number"> /// <item><description><c>s[s.Length - n]</c> and offers to change that to <c>s[^n]</c></description></item> /// <item><description></description><c>s.Get(s.Length - n)</c> and offers to change that to <c>s.Get(^n)</c></item> /// </list> /// /// <para>In order to do convert between indexers, the type must look 'indexable'. Meaning, it must /// have an <see cref="int"/>-returning property called <c>Length</c> or <c>Count</c>, and it must have both an /// <see cref="int"/>-indexer, and a <see cref="T:System.Index"/>-indexer. In order to convert between methods, the type /// must have identical overloads except that one takes an <see cref="int"/>, and the other a <see cref="T:System.Index"/>.</para> /// /// <para>It is assumed that if the type follows this shape that it is well behaved and that this /// transformation will preserve semantics. If this assumption is not good in practice, we /// could always limit the feature to only work on an allow list of known safe types.</para> /// /// <para>Note that this feature only works if the code literally has <c>expr1.Length - expr2</c>. If /// code has this, and is calling into a method that takes either an <see cref="int"/> or a <see cref="T:System.Index"/>, /// it feels very safe to assume this is well behaved and switching to <c>^expr2</c> is going to /// preserve semantics.</para> /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Required to avoid ambiguous reference warnings.")] internal partial class CSharpUseIndexOperatorDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpUseIndexOperatorDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseIndexOperatorDiagnosticId, EnforceOnBuildValues.UseIndexOperator, CSharpCodeStyleOptions.PreferIndexOperator, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_index_operator), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Indexing_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(startContext => { // We're going to be checking every property-reference and invocation in the // compilation. Cache information we compute in this object so we don't have to // continually recompute it. var compilation = startContext.Compilation; var infoCache = new InfoCache(compilation); // The System.Index type is always required to offer this fix. if (infoCache.IndexType == null) { return; } // Register to hear property references, so we can hear about calls to indexers // like: s[s.Length - n] context.RegisterOperationAction( c => AnalyzePropertyReference(c, infoCache), OperationKind.PropertyReference); // Register to hear about methods for: s.Get(s.Length - n) context.RegisterOperationAction( c => AnalyzeInvocation(c, infoCache), OperationKind.Invocation); var arrayType = compilation.GetSpecialType(SpecialType.System_Array); var arrayLengthProperty = TryGetNoArgInt32Property(arrayType, nameof(Array.Length)); if (arrayLengthProperty != null) { // Array indexing is represented with a different operation kind. Register // specifically for that. context.RegisterOperationAction( c => AnalyzeArrayElementReference(c, infoCache, arrayLengthProperty), OperationKind.ArrayElementReference); } }); } private void AnalyzeInvocation( OperationAnalysisContext context, InfoCache infoCache) { var cancellationToken = context.CancellationToken; var invocationOperation = (IInvocationOperation)context.Operation; if (invocationOperation.Arguments.Length != 1) { return; } AnalyzeInvokedMember( context, infoCache, invocationOperation.Instance, invocationOperation.TargetMethod, invocationOperation.Arguments[0].Value, lengthLikePropertyOpt: null, cancellationToken); } private void AnalyzePropertyReference( OperationAnalysisContext context, InfoCache infoCache) { var cancellationToken = context.CancellationToken; var propertyReference = (IPropertyReferenceOperation)context.Operation; // Only analyze indexer calls. if (!propertyReference.Property.IsIndexer) { return; } if (propertyReference.Arguments.Length != 1) { return; } AnalyzeInvokedMember( context, infoCache, propertyReference.Instance, propertyReference.Property.GetMethod, propertyReference.Arguments[0].Value, lengthLikePropertyOpt: null, cancellationToken); } private void AnalyzeArrayElementReference( OperationAnalysisContext context, InfoCache infoCache, IPropertySymbol arrayLengthProperty) { var cancellationToken = context.CancellationToken; var arrayElementReference = (IArrayElementReferenceOperation)context.Operation; // Has to be a single-dimensional element access. if (arrayElementReference.Indices.Length != 1) { return; } AnalyzeInvokedMember( context, infoCache, arrayElementReference.ArrayReference, targetMethodOpt: null, arrayElementReference.Indices[0], lengthLikePropertyOpt: arrayLengthProperty, cancellationToken); } private void AnalyzeInvokedMember( OperationAnalysisContext context, InfoCache infoCache, IOperation instance, IMethodSymbol targetMethodOpt, IOperation argumentValue, IPropertySymbol lengthLikePropertyOpt, CancellationToken cancellationToken) { // look for `s[s.Length - value]` or `s.Get(s.Length- value)`. // Needs to have the one arg for `s.Length - value`, and that arg needs to be // a subtraction. if (instance is null || !IsSubtraction(argumentValue, out var subtraction)) { return; } if (!(subtraction.Syntax is BinaryExpressionSyntax binaryExpression)) { return; } // Only supported on C# 8 and above. var syntaxTree = binaryExpression.SyntaxTree; var parseOptions = (CSharpParseOptions)syntaxTree.Options; if (parseOptions.LanguageVersion < LanguageVersion.CSharp8) { return; } // Don't bother analyzing if the user doesn't like using Index/Range operators. var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferIndexOperator, syntaxTree, cancellationToken); if (!option.Value) { return; } // Ok, looks promising. We're indexing in with some subtraction expression. Examine the // type this indexer is in to see if there's another member that takes a System.Index // that we can convert to. // // Also ensure that the left side of the subtraction : `s.Length - value` is actually // getting the length off the same instance we're indexing into. lengthLikePropertyOpt ??= TryGetLengthLikeProperty(infoCache, targetMethodOpt); if (lengthLikePropertyOpt == null || !IsInstanceLengthCheck(lengthLikePropertyOpt, instance, subtraction.LeftOperand)) { return; } // Everything looks good. We can update this to use the System.Index member instead. context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, binaryExpression.GetLocation(), option.Notification.Severity, ImmutableArray<Location>.Empty, ImmutableDictionary<string, string>.Empty)); } private static IPropertySymbol TryGetLengthLikeProperty(InfoCache infoCache, IMethodSymbol targetMethodOpt) => targetMethodOpt != null && infoCache.TryGetMemberInfo(targetMethodOpt, out var memberInfo) ? memberInfo.LengthLikeProperty : null; } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/Core/Implementation/BraceMatching/BraceHighlightingViewTaggerProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { [Export(typeof(IViewTaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [TagType(typeof(BraceHighlightTag))] internal class BraceHighlightingViewTaggerProvider : AsynchronousViewTaggerProvider<BraceHighlightTag> { private readonly IBraceMatchingService _braceMatcherService; protected override IEnumerable<Option2<bool>> Options => SpecializedCollections.SingletonEnumerable(InternalFeatureOnOffOptions.BraceMatching); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public BraceHighlightingViewTaggerProvider( IThreadingContext threadingContext, IBraceMatchingService braceMatcherService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, listenerProvider.GetListener(FeatureAttribute.BraceHighlighting)) { _braceMatcherService = braceMatcherService; } protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate; protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer) { return TaggerEventSources.Compose( TaggerEventSources.OnTextChanged(subjectBuffer), TaggerEventSources.OnCaretPositionChanged(textView, subjectBuffer), TaggerEventSources.OnParseOptionChanged(subjectBuffer)); } protected override Task ProduceTagsAsync(TaggerContext<BraceHighlightTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition) { var document = documentSnapshotSpan.Document; if (!caretPosition.HasValue || document == null) { return Task.CompletedTask; } return ProduceTagsAsync(context, document, documentSnapshotSpan.SnapshotSpan.Snapshot, caretPosition.Value); } internal async Task ProduceTagsAsync(TaggerContext<BraceHighlightTag> context, Document document, ITextSnapshot snapshot, int position) { using (Logger.LogBlock(FunctionId.Tagger_BraceHighlighting_TagProducer_ProduceTags, context.CancellationToken)) { if (position >= 0 && position <= snapshot.Length) { var (bracesLeftOfPosition, bracesRightOfPosition) = await GetAllMatchingBracesAsync( _braceMatcherService, document, position, context.CancellationToken).ConfigureAwait(false); AddBraces(context, snapshot, bracesLeftOfPosition); AddBraces(context, snapshot, bracesRightOfPosition); } } } /// <summary> /// Given code like ()^() (where ^ is the caret position), returns the two pairs of /// matching braces on the left and the right of the position. Note: a brace matching /// pair is only returned if the position is on the left-side of hte start brace, or the /// right side of end brace. So, for example, if you have (^()), then only the inner /// braces are returned as the position is not on the right-side of the outer braces. /// /// This function also works for multi-character braces i.e. ([ ]) In this case, /// the rule is that the position has to be on the left side of the start brace, or /// inside the start brace (but not at the end). So, ^([ ]) will return this /// as a brace match, as will (^[ ]). But ([^ ]) will not. /// /// The same goes for the braces on the the left of the caret. i.e.: ([ ])^ /// will return the braces on the left, as will ([ ]^). But ([ ^]) will not. /// </summary> private static async Task<(BraceMatchingResult? leftOfPosition, BraceMatchingResult? rightOfPosition)> GetAllMatchingBracesAsync( IBraceMatchingService service, Document document, int position, CancellationToken cancellationToken) { // These are the matching spans when checking the token to the right of the position. var rightOfPosition = await service.GetMatchingBracesAsync(document, position, cancellationToken).ConfigureAwait(false); // The braces to the right of the position should only be added if the position is // actually within the span of the start brace. Note that this is what we want for // single character braces as well as multi char braces. i.e. if the user has: // // ^{ } // then { and } are matching braces. // {^ } // then { and } are not matching braces. // // ^<@ @> // then <@ and @> are matching braces. // <^@ @> // then <@ and @> are matching braces. // <@^ @> // then <@ and @> are not matching braces. if (rightOfPosition.HasValue && !rightOfPosition.Value.LeftSpan.Contains(position)) { // Not a valid match. rightOfPosition = null; } if (position == 0) { // We're at the start of the document, can't find braces to the left of the position. return (leftOfPosition: null, rightOfPosition); } // See if we're touching the end of some construct. i.e.: // // { }^ // <@ @>^ // <@ @^> // // But not // // { ^} // <@ ^@> var leftOfPosition = await service.GetMatchingBracesAsync(document, position - 1, cancellationToken).ConfigureAwait(false); if (leftOfPosition.HasValue && position <= leftOfPosition.Value.RightSpan.End && position > leftOfPosition.Value.RightSpan.Start) { // Found a valid pair on the left of us. return (leftOfPosition, rightOfPosition); } // No valid pair of braces on the left of us. return (leftOfPosition: null, rightOfPosition); } private static void AddBraces( TaggerContext<BraceHighlightTag> context, ITextSnapshot snapshot, BraceMatchingResult? braces) { if (braces.HasValue) { context.AddTag(snapshot.GetTagSpan(braces.Value.LeftSpan.ToSpan(), BraceHighlightTag.StartTag)); context.AddTag(snapshot.GetTagSpan(braces.Value.RightSpan.ToSpan(), BraceHighlightTag.EndTag)); } } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { [Export(typeof(IViewTaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [TagType(typeof(BraceHighlightTag))] internal class BraceHighlightingViewTaggerProvider : AsynchronousViewTaggerProvider<BraceHighlightTag> { private readonly IBraceMatchingService _braceMatcherService; protected override IEnumerable<Option2<bool>> Options => SpecializedCollections.SingletonEnumerable(InternalFeatureOnOffOptions.BraceMatching); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public BraceHighlightingViewTaggerProvider( IThreadingContext threadingContext, IBraceMatchingService braceMatcherService, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, listenerProvider.GetListener(FeatureAttribute.BraceHighlighting)) { _braceMatcherService = braceMatcherService; } protected override TaggerDelay EventChangeDelay => TaggerDelay.NearImmediate; protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer) { return TaggerEventSources.Compose( TaggerEventSources.OnTextChanged(subjectBuffer), TaggerEventSources.OnCaretPositionChanged(textView, subjectBuffer), TaggerEventSources.OnParseOptionChanged(subjectBuffer)); } protected override Task ProduceTagsAsync(TaggerContext<BraceHighlightTag> context, DocumentSnapshotSpan documentSnapshotSpan, int? caretPosition) { var document = documentSnapshotSpan.Document; if (!caretPosition.HasValue || document == null) { return Task.CompletedTask; } return ProduceTagsAsync(context, document, documentSnapshotSpan.SnapshotSpan.Snapshot, caretPosition.Value); } internal async Task ProduceTagsAsync(TaggerContext<BraceHighlightTag> context, Document document, ITextSnapshot snapshot, int position) { using (Logger.LogBlock(FunctionId.Tagger_BraceHighlighting_TagProducer_ProduceTags, context.CancellationToken)) { if (position >= 0 && position <= snapshot.Length) { var (bracesLeftOfPosition, bracesRightOfPosition) = await GetAllMatchingBracesAsync( _braceMatcherService, document, position, context.CancellationToken).ConfigureAwait(false); AddBraces(context, snapshot, bracesLeftOfPosition); AddBraces(context, snapshot, bracesRightOfPosition); } } } /// <summary> /// Given code like ()^() (where ^ is the caret position), returns the two pairs of /// matching braces on the left and the right of the position. Note: a brace matching /// pair is only returned if the position is on the left-side of hte start brace, or the /// right side of end brace. So, for example, if you have (^()), then only the inner /// braces are returned as the position is not on the right-side of the outer braces. /// /// This function also works for multi-character braces i.e. ([ ]) In this case, /// the rule is that the position has to be on the left side of the start brace, or /// inside the start brace (but not at the end). So, ^([ ]) will return this /// as a brace match, as will (^[ ]). But ([^ ]) will not. /// /// The same goes for the braces on the the left of the caret. i.e.: ([ ])^ /// will return the braces on the left, as will ([ ]^). But ([ ^]) will not. /// </summary> private static async Task<(BraceMatchingResult? leftOfPosition, BraceMatchingResult? rightOfPosition)> GetAllMatchingBracesAsync( IBraceMatchingService service, Document document, int position, CancellationToken cancellationToken) { // These are the matching spans when checking the token to the right of the position. var rightOfPosition = await service.GetMatchingBracesAsync(document, position, cancellationToken).ConfigureAwait(false); // The braces to the right of the position should only be added if the position is // actually within the span of the start brace. Note that this is what we want for // single character braces as well as multi char braces. i.e. if the user has: // // ^{ } // then { and } are matching braces. // {^ } // then { and } are not matching braces. // // ^<@ @> // then <@ and @> are matching braces. // <^@ @> // then <@ and @> are matching braces. // <@^ @> // then <@ and @> are not matching braces. if (rightOfPosition.HasValue && !rightOfPosition.Value.LeftSpan.Contains(position)) { // Not a valid match. rightOfPosition = null; } if (position == 0) { // We're at the start of the document, can't find braces to the left of the position. return (leftOfPosition: null, rightOfPosition); } // See if we're touching the end of some construct. i.e.: // // { }^ // <@ @>^ // <@ @^> // // But not // // { ^} // <@ ^@> var leftOfPosition = await service.GetMatchingBracesAsync(document, position - 1, cancellationToken).ConfigureAwait(false); if (leftOfPosition.HasValue && position <= leftOfPosition.Value.RightSpan.End && position > leftOfPosition.Value.RightSpan.Start) { // Found a valid pair on the left of us. return (leftOfPosition, rightOfPosition); } // No valid pair of braces on the left of us. return (leftOfPosition: null, rightOfPosition); } private static void AddBraces( TaggerContext<BraceHighlightTag> context, ITextSnapshot snapshot, BraceMatchingResult? braces) { if (braces.HasValue) { context.AddTag(snapshot.GetTagSpan(braces.Value.LeftSpan.ToSpan(), BraceHighlightTag.StartTag)); context.AddTag(snapshot.GetTagSpan(braces.Value.RightSpan.ToSpan(), BraceHighlightTag.EndTag)); } } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/TypeImportCompletionProvider.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.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(TypeImportCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(PropertySubpatternCompletionProvider))] [Shared] internal sealed class TypeImportCompletionProvider : AbstractTypeImportCompletionProvider<UsingDirectiveSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TypeImportCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; protected override ImmutableArray<string> GetImportedNamespaces( SyntaxNode location, SemanticModel semanticModel, CancellationToken cancellationToken) => ImportCompletionProviderHelper.GetImportedNamespaces(location, semanticModel); protected override Task<SyntaxContext> CreateContextAsync(Document document, int position, bool usePartialSemantic, CancellationToken cancellationToken) => ImportCompletionProviderHelper.CreateContextAsync(document, position, usePartialSemantic, cancellationToken); protected override bool IsFinalSemicolonOfUsingOrExtern(SyntaxNode directive, SyntaxToken token) { if (token.IsKind(SyntaxKind.None) || token.IsMissing) return false; return directive switch { UsingDirectiveSyntax usingDirective => usingDirective.SemicolonToken == token, ExternAliasDirectiveSyntax externAliasDirective => externAliasDirective.SemicolonToken == token, _ => false, }; } protected override async Task<bool> ShouldProvideParenthesisCompletionAsync( Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) { if (commitKey is ';' or '.') { // Only consider add '()' if the type is used under object creation context var position = item.Span.Start; var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return syntaxTree.IsObjectCreationTypeContext(position, leftToken, cancellationToken); } return false; } protected override ImmutableArray<UsingDirectiveSyntax> GetAliasDeclarationNodes(SyntaxNode node) => node.GetEnclosingUsingDirectives() .Where(n => n.Alias != null) .ToImmutableArray(); } }
// Licensed to the .NET Foundation under one or more 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.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(TypeImportCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(PropertySubpatternCompletionProvider))] [Shared] internal sealed class TypeImportCompletionProvider : AbstractTypeImportCompletionProvider<UsingDirectiveSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TypeImportCompletionProvider() { } public override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) => CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); public override ImmutableHashSet<char> TriggerCharacters { get; } = CompletionUtilities.CommonTriggerCharacters; protected override ImmutableArray<string> GetImportedNamespaces( SyntaxNode location, SemanticModel semanticModel, CancellationToken cancellationToken) => ImportCompletionProviderHelper.GetImportedNamespaces(location, semanticModel); protected override Task<SyntaxContext> CreateContextAsync(Document document, int position, bool usePartialSemantic, CancellationToken cancellationToken) => ImportCompletionProviderHelper.CreateContextAsync(document, position, usePartialSemantic, cancellationToken); protected override bool IsFinalSemicolonOfUsingOrExtern(SyntaxNode directive, SyntaxToken token) { if (token.IsKind(SyntaxKind.None) || token.IsMissing) return false; return directive switch { UsingDirectiveSyntax usingDirective => usingDirective.SemicolonToken == token, ExternAliasDirectiveSyntax externAliasDirective => externAliasDirective.SemicolonToken == token, _ => false, }; } protected override async Task<bool> ShouldProvideParenthesisCompletionAsync( Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken) { if (commitKey is ';' or '.') { // Only consider add '()' if the type is used under object creation context var position = item.Span.Start; var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return syntaxTree.IsObjectCreationTypeContext(position, leftToken, cancellationToken); } return false; } protected override ImmutableArray<UsingDirectiveSyntax> GetAliasDeclarationNodes(SyntaxNode node) => node.GetEnclosingUsingDirectives() .Where(n => n.Alias != null) .ToImmutableArray(); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Workspaces/CoreTestUtilities/MEF/FeaturesTestCompositions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.UnitTests.Remote; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class FeaturesTestCompositions { public static readonly TestComposition Features = TestComposition.Empty .AddAssemblies(MefHostServices.DefaultAssemblies) .AddParts( typeof(TestSerializerService.Factory), typeof(MockWorkspaceEventListenerProvider), // by default, avoid running Solution Crawler and other services that start in workspace event listeners typeof(TestErrorReportingService)); // mocks the info-bar error reporting public static readonly TestComposition RemoteHost = TestComposition.Empty .AddAssemblies(RemoteWorkspaceManager.RemoteHostAssemblies) .AddParts(typeof(TestSerializerService.Factory)); public static TestComposition WithTestHostParts(this TestComposition composition, TestHost host) => (host == TestHost.InProcess) ? composition : composition.AddAssemblies(typeof(RemoteWorkspacesResources).Assembly).AddParts(typeof(InProcRemoteHostClientProvider.Factory)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.UnitTests.Remote; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class FeaturesTestCompositions { public static readonly TestComposition Features = TestComposition.Empty .AddAssemblies(MefHostServices.DefaultAssemblies) .AddParts( typeof(TestSerializerService.Factory), typeof(MockWorkspaceEventListenerProvider), // by default, avoid running Solution Crawler and other services that start in workspace event listeners typeof(TestErrorReportingService)); // mocks the info-bar error reporting public static readonly TestComposition RemoteHost = TestComposition.Empty .AddAssemblies(RemoteWorkspaceManager.RemoteHostAssemblies) .AddParts(typeof(TestSerializerService.Factory)); public static TestComposition WithTestHostParts(this TestComposition composition, TestHost host) => (host == TestHost.InProcess) ? composition : composition.AddAssemblies(typeof(RemoteWorkspacesResources).Assembly).AddParts(typeof(InProcRemoteHostClientProvider.Factory)); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptLanguageDebugInfoService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [Shared] [ExportLanguageService(typeof(ILanguageDebugInfoService), InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptLanguageDebugInfoService : ILanguageDebugInfoService { private readonly IVSTypeScriptLanguageDebugInfoServiceImplementation _implementation; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptLanguageDebugInfoService(IVSTypeScriptLanguageDebugInfoServiceImplementation implementation) => _implementation = implementation; public async Task<DebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _implementation.GetDataTipInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; public async Task<DebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _implementation.GetLocationInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [Shared] [ExportLanguageService(typeof(ILanguageDebugInfoService), InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptLanguageDebugInfoService : ILanguageDebugInfoService { private readonly IVSTypeScriptLanguageDebugInfoServiceImplementation _implementation; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptLanguageDebugInfoService(IVSTypeScriptLanguageDebugInfoServiceImplementation implementation) => _implementation = implementation; public async Task<DebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _implementation.GetDataTipInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; public async Task<DebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken) => (await _implementation.GetLocationInfoAsync(document, position, cancellationToken).ConfigureAwait(false)).UnderlyingObject; } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Portable/Binder/ForEachLoopBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A loop binder that (1) knows how to bind foreach loops and (2) has the foreach iteration variable in scope. /// </summary> /// <remarks> /// This binder produces BoundForEachStatements. The lowering described in the spec is performed in ControlFlowRewriter. /// </remarks> internal sealed class ForEachLoopBinder : LoopBinder { private const string GetEnumeratorMethodName = WellKnownMemberNames.GetEnumeratorMethodName; private const string CurrentPropertyName = WellKnownMemberNames.CurrentPropertyName; private const string MoveNextMethodName = WellKnownMemberNames.MoveNextMethodName; private const string GetAsyncEnumeratorMethodName = WellKnownMemberNames.GetAsyncEnumeratorMethodName; private const string MoveNextAsyncMethodName = WellKnownMemberNames.MoveNextAsyncMethodName; private readonly CommonForEachStatementSyntax _syntax; private SourceLocalSymbol IterationVariable { get { return (_syntax.Kind() == SyntaxKind.ForEachStatement) ? (SourceLocalSymbol)this.Locals[0] : null; } } private bool IsAsync => _syntax.AwaitKeyword != default; public ForEachLoopBinder(Binder enclosing, CommonForEachStatementSyntax syntax) : base(enclosing) { Debug.Assert(syntax != null); _syntax = syntax; } protected override ImmutableArray<LocalSymbol> BuildLocals() { switch (_syntax.Kind()) { case SyntaxKind.ForEachVariableStatement: { var syntax = (ForEachVariableStatementSyntax)_syntax; var locals = ArrayBuilder<LocalSymbol>.GetInstance(); CollectLocalsFromDeconstruction( syntax.Variable, LocalDeclarationKind.ForEachIterationVariable, locals, syntax); return locals.ToImmutableAndFree(); } case SyntaxKind.ForEachStatement: { var syntax = (ForEachStatementSyntax)_syntax; var iterationVariable = SourceLocalSymbol.MakeForeachLocal( (MethodSymbol)this.ContainingMemberOrLambda, this, syntax.Type, syntax.Identifier, syntax.Expression); return ImmutableArray.Create<LocalSymbol>(iterationVariable); } default: throw ExceptionUtilities.UnexpectedValue(_syntax.Kind()); } } internal void CollectLocalsFromDeconstruction( ExpressionSyntax declaration, LocalDeclarationKind kind, ArrayBuilder<LocalSymbol> locals, SyntaxNode deconstructionStatement, Binder enclosingBinderOpt = null) { switch (declaration.Kind()) { case SyntaxKind.TupleExpression: { var tuple = (TupleExpressionSyntax)declaration; foreach (var arg in tuple.Arguments) { CollectLocalsFromDeconstruction(arg.Expression, kind, locals, deconstructionStatement, enclosingBinderOpt); } break; } case SyntaxKind.DeclarationExpression: { var declarationExpression = (DeclarationExpressionSyntax)declaration; CollectLocalsFromDeconstruction( declarationExpression.Designation, declarationExpression.Type, kind, locals, deconstructionStatement, enclosingBinderOpt); break; } case SyntaxKind.IdentifierName: break; default: // In broken code, we can have an arbitrary expression here. Collect its expression variables. ExpressionVariableFinder.FindExpressionVariables(this, locals, declaration); break; } } internal void CollectLocalsFromDeconstruction( VariableDesignationSyntax designation, TypeSyntax closestTypeSyntax, LocalDeclarationKind kind, ArrayBuilder<LocalSymbol> locals, SyntaxNode deconstructionStatement, Binder enclosingBinderOpt) { switch (designation.Kind()) { case SyntaxKind.SingleVariableDesignation: { var single = (SingleVariableDesignationSyntax)designation; SourceLocalSymbol localSymbol = SourceLocalSymbol.MakeDeconstructionLocal( this.ContainingMemberOrLambda, this, enclosingBinderOpt ?? this, closestTypeSyntax, single.Identifier, kind, deconstructionStatement); locals.Add(localSymbol); break; } case SyntaxKind.ParenthesizedVariableDesignation: { var tuple = (ParenthesizedVariableDesignationSyntax)designation; foreach (var d in tuple.Variables) { CollectLocalsFromDeconstruction(d, closestTypeSyntax, kind, locals, deconstructionStatement, enclosingBinderOpt); } break; } case SyntaxKind.DiscardDesignation: break; default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } /// <summary> /// Bind the ForEachStatementSyntax at the root of this binder. /// </summary> internal override BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { BoundForEachStatement result = BindForEachPartsWorker(diagnostics, originalBinder); return result; } /// <summary> /// Like BindForEachParts, but only bind the deconstruction part of the foreach, for purpose of inferring the types of the declared locals. /// </summary> internal override BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) { // Use the right binder to avoid seeing iteration variable BoundExpression collectionExpr = originalBinder.GetBinder(_syntax.Expression).BindRValueWithoutTargetType(_syntax.Expression, diagnostics); var builder = new ForEachEnumeratorInfo.Builder(); TypeWithAnnotations inferredType; bool hasErrors = !GetEnumeratorInfoAndInferCollectionElementType(ref builder, ref collectionExpr, diagnostics, out inferredType); ExpressionSyntax variables = ((ForEachVariableStatementSyntax)_syntax).Variable; // Tracking narrowest safe-to-escape scope by default, the proper val escape will be set when doing full binding of the foreach statement var valuePlaceholder = new BoundDeconstructValuePlaceholder(_syntax.Expression, this.LocalScopeDepth, inferredType.Type ?? CreateErrorType("var")); DeclarationExpressionSyntax declaration = null; ExpressionSyntax expression = null; BoundDeconstructionAssignmentOperator deconstruction = BindDeconstruction( variables, variables, right: _syntax.Expression, diagnostics: diagnostics, rightPlaceholder: valuePlaceholder, declaration: ref declaration, expression: ref expression); return new BoundExpressionStatement(_syntax, deconstruction); } private BoundForEachStatement BindForEachPartsWorker(BindingDiagnosticBag diagnostics, Binder originalBinder) { // Use the right binder to avoid seeing iteration variable BoundExpression collectionExpr = originalBinder.GetBinder(_syntax.Expression).BindRValueWithoutTargetType(_syntax.Expression, diagnostics); var builder = new ForEachEnumeratorInfo.Builder(); TypeWithAnnotations inferredType; bool hasErrors = !GetEnumeratorInfoAndInferCollectionElementType(ref builder, ref collectionExpr, diagnostics, out inferredType); // These occur when special types are missing or malformed, or the patterns are incompletely implemented. hasErrors |= builder.IsIncomplete; BoundAwaitableInfo awaitInfo = null; MethodSymbol getEnumeratorMethod = builder.GetEnumeratorInfo?.Method; if (getEnumeratorMethod != null) { originalBinder.CheckImplicitThisCopyInReadOnlyMember(collectionExpr, getEnumeratorMethod, diagnostics); if (getEnumeratorMethod.IsExtensionMethod && !hasErrors) { var messageId = IsAsync ? MessageID.IDS_FeatureExtensionGetAsyncEnumerator : MessageID.IDS_FeatureExtensionGetEnumerator; hasErrors |= !messageId.CheckFeatureAvailability( diagnostics, Compilation, collectionExpr.Syntax.Location); if (getEnumeratorMethod.ParameterRefKinds is { IsDefault: false } refKinds && refKinds[0] == RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_RefLvalueExpected, collectionExpr.Syntax); hasErrors = true; } } } if (IsAsync) { var expr = _syntax.Expression; ReportBadAwaitDiagnostics(expr, _syntax.AwaitKeyword.GetLocation(), diagnostics, ref hasErrors); var placeholder = new BoundAwaitableValuePlaceholder(expr, valEscape: this.LocalScopeDepth, builder.MoveNextInfo?.Method.ReturnType ?? CreateErrorType()); awaitInfo = BindAwaitInfo(placeholder, expr, diagnostics, ref hasErrors); if (!hasErrors && awaitInfo.GetResult?.ReturnType.SpecialType != SpecialType.System_Boolean) { diagnostics.Add(ErrorCode.ERR_BadGetAsyncEnumerator, expr.Location, getEnumeratorMethod.ReturnTypeWithAnnotations, getEnumeratorMethod); hasErrors = true; } } TypeWithAnnotations iterationVariableType; BoundTypeExpression boundIterationVariableType; bool hasNameConflicts = false; BoundForEachDeconstructStep deconstructStep = null; BoundExpression iterationErrorExpression = null; uint collectionEscape = GetValEscape(collectionExpr, this.LocalScopeDepth); switch (_syntax.Kind()) { case SyntaxKind.ForEachStatement: { var node = (ForEachStatementSyntax)_syntax; // Check for local variable conflicts in the *enclosing* binder; obviously the *current* // binder has a local that matches! hasNameConflicts = originalBinder.ValidateDeclarationNameConflictsInScope(IterationVariable, diagnostics); // If the type in syntax is "var", then the type should be set explicitly so that the // Type property doesn't fail. TypeSyntax typeSyntax = node.Type.SkipRef(out _); bool isVar; AliasSymbol alias; TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar, out alias); if (isVar) { declType = inferredType.HasType ? inferredType : TypeWithAnnotations.Create(CreateErrorType("var")); } else { Debug.Assert(declType.HasType); } iterationVariableType = declType; boundIterationVariableType = new BoundTypeExpression(typeSyntax, alias, iterationVariableType); SourceLocalSymbol local = this.IterationVariable; local.SetTypeWithAnnotations(declType); local.SetValEscape(collectionEscape); if (local.RefKind != RefKind.None) { // The ref-escape of a ref-returning property is decided // by the value escape of its receiver, in this case the // collection local.SetRefEscape(collectionEscape); if (CheckRefLocalInAsyncOrIteratorMethod(local.IdentifierToken, diagnostics)) { hasErrors = true; } } if (!hasErrors) { BindValueKind requiredCurrentKind; switch (local.RefKind) { case RefKind.None: requiredCurrentKind = BindValueKind.RValue; break; case RefKind.Ref: requiredCurrentKind = BindValueKind.Assignable | BindValueKind.RefersToLocation; break; case RefKind.RefReadOnly: requiredCurrentKind = BindValueKind.RefersToLocation; break; default: throw ExceptionUtilities.UnexpectedValue(local.RefKind); } hasErrors |= !CheckMethodReturnValueKind( builder.CurrentPropertyGetter, callSyntaxOpt: null, collectionExpr.Syntax, requiredCurrentKind, checkingReceiver: false, diagnostics); } break; } case SyntaxKind.ForEachVariableStatement: { var node = (ForEachVariableStatementSyntax)_syntax; iterationVariableType = inferredType.HasType ? inferredType : TypeWithAnnotations.Create(CreateErrorType("var")); var variables = node.Variable; if (variables.IsDeconstructionLeft()) { var valuePlaceholder = new BoundDeconstructValuePlaceholder(_syntax.Expression, collectionEscape, iterationVariableType.Type).MakeCompilerGenerated(); DeclarationExpressionSyntax declaration = null; ExpressionSyntax expression = null; BoundDeconstructionAssignmentOperator deconstruction = BindDeconstruction( variables, variables, right: _syntax.Expression, diagnostics: diagnostics, rightPlaceholder: valuePlaceholder, declaration: ref declaration, expression: ref expression); if (expression != null) { // error: must declare foreach loop iteration variables. Error(diagnostics, ErrorCode.ERR_MustDeclareForeachIteration, variables); hasErrors = true; } deconstructStep = new BoundForEachDeconstructStep(variables, deconstruction, valuePlaceholder).MakeCompilerGenerated(); } else { // Bind the expression for error recovery, but discard all new diagnostics iterationErrorExpression = BindExpression(node.Variable, BindingDiagnosticBag.Discarded); if (iterationErrorExpression.Kind == BoundKind.DiscardExpression) { iterationErrorExpression = ((BoundDiscardExpression)iterationErrorExpression).FailInference(this, diagnosticsOpt: null); } hasErrors = true; if (!node.HasErrors) { Error(diagnostics, ErrorCode.ERR_MustDeclareForeachIteration, variables); } } boundIterationVariableType = new BoundTypeExpression(variables, aliasOpt: null, typeWithAnnotations: iterationVariableType).MakeCompilerGenerated(); break; } default: throw ExceptionUtilities.UnexpectedValue(_syntax.Kind()); } BoundStatement body = originalBinder.BindPossibleEmbeddedStatement(_syntax.Statement, diagnostics); // NOTE: in error cases, binder may collect all kind of variables, not just formally declared iteration variables. // As a matter of error recovery, we will treat such variables the same as the iteration variables. // I.E. - they will be considered declared and assigned in each iteration step. ImmutableArray<LocalSymbol> iterationVariables = this.Locals; Debug.Assert(hasErrors || _syntax.HasErrors || iterationVariables.All(local => local.DeclarationKind == LocalDeclarationKind.ForEachIterationVariable), "Should not have iteration variables that are not ForEachIterationVariable in valid code"); hasErrors = hasErrors || boundIterationVariableType.HasErrors || iterationVariableType.Type.IsErrorType(); // Skip the conversion checks and array/enumerator differentiation if we know we have an error (except local name conflicts). if (hasErrors) { return new BoundForEachStatement( _syntax, enumeratorInfoOpt: null, // can't be sure that it's complete elementConversion: default, boundIterationVariableType, iterationVariables, iterationErrorExpression, collectionExpr, deconstructStep, awaitInfo, body, CheckOverflowAtRuntime, this.BreakLabel, this.ContinueLabel, hasErrors); } hasErrors |= hasNameConflicts; var foreachKeyword = _syntax.ForEachKeyword; ReportDiagnosticsIfObsolete(diagnostics, getEnumeratorMethod, foreachKeyword, hasBaseReceiver: false); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, getEnumeratorMethod, foreachKeyword.GetLocation(), isDelegateConversion: false); // MoveNext is an instance method, so it does not need to have unmanaged callers only diagnostics reported. // Either a diagnostic was reported at the declaration of the method (for the invalid attribute), or MoveNext // is marked as not supported and we won't get here in the first place (for metadata import). ReportDiagnosticsIfObsolete(diagnostics, builder.MoveNextInfo.Method, foreachKeyword, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter, foreachKeyword, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter.AssociatedSymbol, foreachKeyword, hasBaseReceiver: false); // We want to convert from inferredType in the array/string case and builder.ElementType in the enumerator case, // but it turns out that these are equivalent (when both are available). CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion elementConversion = this.Conversions.ClassifyConversionFromType(inferredType.Type, iterationVariableType.Type, ref useSiteInfo, forCast: true); if (!elementConversion.IsValid) { ImmutableArray<MethodSymbol> originalUserDefinedConversions = elementConversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { diagnostics.Add(ErrorCode.ERR_AmbigUDConv, foreachKeyword.GetLocation(), originalUserDefinedConversions[0], originalUserDefinedConversions[1], inferredType.Type, iterationVariableType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, inferredType.Type, iterationVariableType.Type); diagnostics.Add(ErrorCode.ERR_NoExplicitConv, foreachKeyword.GetLocation(), distinguisher.First, distinguisher.Second); } hasErrors = true; } else { ReportDiagnosticsIfObsolete(diagnostics, elementConversion, _syntax.ForEachKeyword, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(_syntax.ForEachKeyword, elementConversion, diagnostics); } // Spec (§8.8.4): // If the type X of expression is dynamic then there is an implicit conversion from >>expression<< (not the type of the expression) // to the System.Collections.IEnumerable interface (§6.1.8). builder.CollectionConversion = this.Conversions.ClassifyConversionFromExpression(collectionExpr, builder.CollectionType, ref useSiteInfo); builder.CurrentConversion = this.Conversions.ClassifyConversionFromType(builder.CurrentPropertyGetter.ReturnType, builder.ElementType, ref useSiteInfo); TypeSymbol getEnumeratorType = getEnumeratorMethod.ReturnType; // we never convert struct enumerators to object - it is done only for null-checks. builder.EnumeratorConversion = getEnumeratorType.IsValueType ? Conversion.Identity : this.Conversions.ClassifyConversionFromType(getEnumeratorType, GetSpecialType(SpecialType.System_Object, diagnostics, _syntax), ref useSiteInfo); if (getEnumeratorType.IsRestrictedType() && (IsDirectlyInIterator || IsInAsyncMethod())) { diagnostics.Add(ErrorCode.ERR_BadSpecialByRefIterator, foreachKeyword.GetLocation(), getEnumeratorType); } diagnostics.Add(_syntax.ForEachKeyword.GetLocation(), useSiteInfo); // Due to the way we extracted the various types, these conversions should always be possible. // CAVEAT: if we're iterating over an array of pointers, the current conversion will fail since we // can't convert from object to a pointer type. Similarly, if we're iterating over an array of // Nullable<Error>, the current conversion will fail because we don't know if an ErrorType is a // value type. This doesn't matter in practice, since we won't actually use the enumerator pattern // when we lower the loop. Debug.Assert(builder.CollectionConversion.IsValid); Debug.Assert(builder.CurrentConversion.IsValid || (builder.ElementType.IsPointerOrFunctionPointer() && collectionExpr.Type.IsArray()) || (builder.ElementType.IsNullableType() && builder.ElementType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single().IsErrorType() && collectionExpr.Type.IsArray())); Debug.Assert(builder.EnumeratorConversion.IsValid || this.Compilation.GetSpecialType(SpecialType.System_Object).TypeKind == TypeKind.Error || !useSiteInfo.Diagnostics.IsNullOrEmpty(), "Conversions to object succeed unless there's a problem with the object type or the source type"); // If user-defined conversions could occur here, we would need to check for ObsoleteAttribute. Debug.Assert((object)builder.CollectionConversion.Method == null, "Conversion from collection expression to collection type should not be user-defined"); Debug.Assert((object)builder.CurrentConversion.Method == null, "Conversion from Current property type to element type should not be user-defined"); Debug.Assert((object)builder.EnumeratorConversion.Method == null, "Conversion from GetEnumerator return type to System.Object should not be user-defined"); // We're wrapping the collection expression in a (non-synthesized) conversion so that its converted // type (i.e. builder.CollectionType) will be available in the binding API. Debug.Assert(!builder.CollectionConversion.IsUserDefined); BoundConversion convertedCollectionExpression = new BoundConversion( collectionExpr.Syntax, collectionExpr, builder.CollectionConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, builder.CollectionType); if (builder.NeedsDisposal && IsAsync) { hasErrors |= GetAwaitDisposeAsyncInfo(ref builder, diagnostics); } Debug.Assert( hasErrors || builder.CollectionConversion.IsIdentity || (builder.CollectionConversion.IsImplicit && (IsIEnumerable(builder.CollectionType) || IsIEnumerableT(builder.CollectionType.OriginalDefinition, IsAsync, Compilation) || builder.GetEnumeratorInfo.Method.IsExtensionMethod)) || // For compat behavior, we can enumerate over System.String even if it's not IEnumerable. That will // result in an explicit reference conversion in the bound nodes, but that conversion won't be emitted. (builder.CollectionConversion.Kind == ConversionKind.ExplicitReference && collectionExpr.Type.SpecialType == SpecialType.System_String)); return new BoundForEachStatement( _syntax, builder.Build(this.Flags), elementConversion, boundIterationVariableType, iterationVariables, iterationErrorExpression, convertedCollectionExpression, deconstructStep, awaitInfo, body, CheckOverflowAtRuntime, this.BreakLabel, this.ContinueLabel, hasErrors); } private bool GetAwaitDisposeAsyncInfo(ref ForEachEnumeratorInfo.Builder builder, BindingDiagnosticBag diagnostics) { var awaitableType = builder.PatternDisposeInfo is null ? this.GetWellKnownType(WellKnownType.System_Threading_Tasks_ValueTask, diagnostics, this._syntax) : builder.PatternDisposeInfo.Method.ReturnType; bool hasErrors = false; var expr = _syntax.Expression; ReportBadAwaitDiagnostics(expr, _syntax.AwaitKeyword.GetLocation(), diagnostics, ref hasErrors); var placeholder = new BoundAwaitableValuePlaceholder(expr, valEscape: this.LocalScopeDepth, awaitableType); builder.DisposeAwaitableInfo = BindAwaitInfo(placeholder, expr, diagnostics, ref hasErrors); return hasErrors; } internal TypeWithAnnotations InferCollectionElementType(BindingDiagnosticBag diagnostics, ExpressionSyntax collectionSyntax) { // Use the right binder to avoid seeing iteration variable BoundExpression collectionExpr = this.GetBinder(collectionSyntax).BindValue(collectionSyntax, diagnostics, BindValueKind.RValue); var builder = new ForEachEnumeratorInfo.Builder(); GetEnumeratorInfoAndInferCollectionElementType(ref builder, ref collectionExpr, diagnostics, out TypeWithAnnotations inferredType); return inferredType; } private bool GetEnumeratorInfoAndInferCollectionElementType(ref ForEachEnumeratorInfo.Builder builder, ref BoundExpression collectionExpr, BindingDiagnosticBag diagnostics, out TypeWithAnnotations inferredType) { bool gotInfo = GetEnumeratorInfo(ref builder, ref collectionExpr, diagnostics); if (!gotInfo) { inferredType = default; } else if (collectionExpr.HasDynamicType()) { // If the enumerator is dynamic, it yields dynamic values inferredType = TypeWithAnnotations.Create(DynamicTypeSymbol.Instance); } else if (collectionExpr.Type.SpecialType == SpecialType.System_String && builder.CollectionType.SpecialType == SpecialType.System_Collections_IEnumerable) { // Reproduce dev11 behavior: we're always going to lower a foreach loop over a string to a for loop // over the string's Chars indexer. Therefore, we should infer "char", regardless of what the spec // indicates the element type is. This actually matters in practice because the System.String in // the portable library doesn't have a pattern GetEnumerator method or implement IEnumerable<char>. inferredType = TypeWithAnnotations.Create(GetSpecialType(SpecialType.System_Char, diagnostics, collectionExpr.Syntax)); } else { inferredType = builder.ElementTypeWithAnnotations; } return gotInfo; } private BoundExpression UnwrapCollectionExpressionIfNullable(BoundExpression collectionExpr, BindingDiagnosticBag diagnostics) { TypeSymbol collectionExprType = collectionExpr.Type; // If collectionExprType is a nullable type, then use the underlying type and take the value (i.e. .Value) of collectionExpr. // This behavior is not spec'd, but it's what Dev10 does. if ((object)collectionExprType != null && collectionExprType.IsNullableType()) { SyntaxNode exprSyntax = collectionExpr.Syntax; MethodSymbol nullableValueGetter = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value, diagnostics, exprSyntax); if ((object)nullableValueGetter != null) { nullableValueGetter = nullableValueGetter.AsMember((NamedTypeSymbol)collectionExprType); // Synthesized call, because we don't want to modify the type in the SemanticModel. return BoundCall.Synthesized( syntax: exprSyntax, receiverOpt: collectionExpr, method: nullableValueGetter); } else { return new BoundBadExpression( exprSyntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create(collectionExpr), collectionExprType.GetNullableUnderlyingType()) { WasCompilerGenerated = true }; // Don't affect the type in the SemanticModel. } } return collectionExpr; } /// <summary> /// The spec describes an algorithm for finding the following types: /// 1) Collection type /// 2) Enumerator type /// 3) Element type /// /// The implementation details are a bit different. If we're iterating over a string or an array, then we don't need to record anything /// but the inferredType (in case the iteration variable is implicitly typed). If we're iterating over anything else, then we want the /// inferred type plus a ForEachEnumeratorInfo.Builder with: /// 1) Collection type /// 2) Element type /// 3) GetEnumerator (or GetAsyncEnumerator) method of the collection type (return type will be the enumerator type from the spec) /// 4) Current property and MoveNext (or MoveNextAsync) method of the enumerator type /// /// The caller will have to do some extra conversion checks before creating a ForEachEnumeratorInfo for the BoundForEachStatement. /// </summary> /// <param name="builder">Builder to fill in (partially, all but conversions).</param> /// <param name="collectionExpr">The expression over which to iterate.</param> /// <param name="diagnostics">Populated with binding diagnostics.</param> /// <returns>Partially populated (all but conversions) or null if there was an error.</returns> private bool GetEnumeratorInfo(ref ForEachEnumeratorInfo.Builder builder, ref BoundExpression collectionExpr, BindingDiagnosticBag diagnostics) { bool isAsync = IsAsync; builder.IsAsync = isAsync; EnumeratorResult found = GetEnumeratorInfo(ref builder, ref collectionExpr, isAsync, diagnostics); switch (found) { case EnumeratorResult.Succeeded: return true; case EnumeratorResult.FailedAndReported: return false; } TypeSymbol collectionExprType = collectionExpr.Type; if (string.IsNullOrEmpty(collectionExprType.Name) && collectionExpr.HasErrors) { return false; } if (collectionExprType.IsErrorType()) { return false; } // Retry with a different assumption about whether the foreach is async var ignoredBuilder = new ForEachEnumeratorInfo.Builder(); bool wrongAsync = GetEnumeratorInfo(ref ignoredBuilder, ref collectionExpr, !isAsync, BindingDiagnosticBag.Discarded) == EnumeratorResult.Succeeded; var errorCode = wrongAsync ? (isAsync ? ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync : ErrorCode.ERR_ForEachMissingMemberWrongAsync) : (isAsync ? ErrorCode.ERR_AwaitForEachMissingMember : ErrorCode.ERR_ForEachMissingMember); diagnostics.Add(errorCode, _syntax.Expression.Location, collectionExprType, isAsync ? GetAsyncEnumeratorMethodName : GetEnumeratorMethodName); return false; } private enum EnumeratorResult { Succeeded, FailedNotReported, FailedAndReported } private EnumeratorResult GetEnumeratorInfo(ref ForEachEnumeratorInfo.Builder builder, ref BoundExpression collectionExpr, bool isAsync, BindingDiagnosticBag diagnostics) { TypeSymbol collectionExprType = collectionExpr.Type; if (collectionExprType is null) // There's no way to enumerate something without a type. { if (!ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) { // Anything else with a null type is a method group or anonymous function diagnostics.Add(ErrorCode.ERR_AnonMethGrpInForEach, _syntax.Expression.Location, collectionExpr.Display); } // CONSIDER: dev10 also reports ERR_ForEachMissingMember (i.e. failed pattern match). return EnumeratorResult.FailedAndReported; } if (collectionExpr.ResultKind == LookupResultKind.NotAValue) { // Short-circuiting to prevent strange behavior in the case where the collection // expression is a type expression and the type is enumerable. Debug.Assert(collectionExpr.HasAnyErrors); // should already have been reported return EnumeratorResult.FailedAndReported; } if (collectionExprType.Kind == SymbolKind.DynamicType && IsAsync) { diagnostics.Add(ErrorCode.ERR_BadDynamicAwaitForEach, _syntax.Expression.Location); return EnumeratorResult.FailedAndReported; } // The spec specifically lists the collection, enumerator, and element types for arrays and dynamic. if (collectionExprType.Kind == SymbolKind.ArrayType || collectionExprType.Kind == SymbolKind.DynamicType) { if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) { return EnumeratorResult.FailedAndReported; } builder = GetDefaultEnumeratorInfo(builder, diagnostics, collectionExprType); return EnumeratorResult.Succeeded; } var unwrappedCollectionExpr = UnwrapCollectionExpressionIfNullable(collectionExpr, diagnostics); var unwrappedCollectionExprType = unwrappedCollectionExpr.Type; if (SatisfiesGetEnumeratorPattern(ref builder, unwrappedCollectionExpr, isAsync, viaExtensionMethod: false, diagnostics)) { collectionExpr = unwrappedCollectionExpr; if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) { return EnumeratorResult.FailedAndReported; } return createPatternBasedEnumeratorResult(ref builder, unwrappedCollectionExpr, isAsync, viaExtensionMethod: false, diagnostics); } if (!isAsync && IsIEnumerable(unwrappedCollectionExprType)) { collectionExpr = unwrappedCollectionExpr; // This indicates a problem with the special IEnumerable type - it should have satisfied the GetEnumerator pattern. diagnostics.Add(ErrorCode.ERR_ForEachMissingMember, _syntax.Expression.Location, unwrappedCollectionExprType, GetEnumeratorMethodName); return EnumeratorResult.FailedAndReported; } if (isAsync && IsIAsyncEnumerable(unwrappedCollectionExprType)) { collectionExpr = unwrappedCollectionExpr; // This indicates a problem with the well-known IAsyncEnumerable type - it should have satisfied the GetAsyncEnumerator pattern. diagnostics.Add(ErrorCode.ERR_AwaitForEachMissingMember, _syntax.Expression.Location, unwrappedCollectionExprType, GetAsyncEnumeratorMethodName); return EnumeratorResult.FailedAndReported; } if (SatisfiesIEnumerableInterfaces(ref builder, unwrappedCollectionExpr, isAsync, diagnostics, unwrappedCollectionExprType) is not EnumeratorResult.FailedNotReported and var result) { collectionExpr = unwrappedCollectionExpr; return result; } // COMPAT: // In some rare cases, like MicroFramework, System.String does not implement foreach pattern. // For compat reasons we must still treat System.String as valid to use in a foreach // Similarly to the cases with array and dynamic, we will default to IEnumerable for binding purposes. // Lowering will not use iterator info with strings, so it is ok. if (!isAsync && collectionExprType.SpecialType == SpecialType.System_String) { if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) { return EnumeratorResult.FailedAndReported; } builder = GetDefaultEnumeratorInfo(builder, diagnostics, collectionExprType); return EnumeratorResult.Succeeded; } if (SatisfiesGetEnumeratorPattern(ref builder, collectionExpr, isAsync, viaExtensionMethod: true, diagnostics)) { return createPatternBasedEnumeratorResult(ref builder, collectionExpr, isAsync, viaExtensionMethod: true, diagnostics); } return EnumeratorResult.FailedNotReported; EnumeratorResult createPatternBasedEnumeratorResult(ref ForEachEnumeratorInfo.Builder builder, BoundExpression collectionExpr, bool isAsync, bool viaExtensionMethod, BindingDiagnosticBag diagnostics) { Debug.Assert((object)builder.GetEnumeratorInfo != null); Debug.Assert(!(viaExtensionMethod && builder.GetEnumeratorInfo.Method.Parameters.IsDefaultOrEmpty)); builder.CollectionType = viaExtensionMethod ? builder.GetEnumeratorInfo.Method.Parameters[0].Type : collectionExpr.Type; if (SatisfiesForEachPattern(ref builder, isAsync, diagnostics)) { builder.ElementTypeWithAnnotations = ((PropertySymbol)builder.CurrentPropertyGetter.AssociatedSymbol).TypeWithAnnotations; GetDisposalInfoForEnumerator(ref builder, collectionExpr, isAsync, diagnostics); return EnumeratorResult.Succeeded; } MethodSymbol getEnumeratorMethod = builder.GetEnumeratorInfo.Method; diagnostics.Add(isAsync ? ErrorCode.ERR_BadGetAsyncEnumerator : ErrorCode.ERR_BadGetEnumerator, _syntax.Expression.Location, getEnumeratorMethod.ReturnType, getEnumeratorMethod); return EnumeratorResult.FailedAndReported; } } private EnumeratorResult SatisfiesIEnumerableInterfaces(ref ForEachEnumeratorInfo.Builder builder, BoundExpression collectionExpr, bool isAsync, BindingDiagnosticBag diagnostics, TypeSymbol unwrappedCollectionExprType) { if (!AllInterfacesContainsIEnumerable(ref builder, unwrappedCollectionExprType, isAsync, diagnostics, out bool foundMultipleGenericIEnumerableInterfaces)) { return EnumeratorResult.FailedNotReported; } if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) { return EnumeratorResult.FailedAndReported; } CSharpSyntaxNode errorLocationSyntax = _syntax.Expression; if (foundMultipleGenericIEnumerableInterfaces) { diagnostics.Add(isAsync ? ErrorCode.ERR_MultipleIAsyncEnumOfT : ErrorCode.ERR_MultipleIEnumOfT, errorLocationSyntax.Location, unwrappedCollectionExprType, isAsync ? this.Compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T) : this.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T)); return EnumeratorResult.FailedAndReported; } Debug.Assert((object)builder.CollectionType != null); NamedTypeSymbol collectionType = (NamedTypeSymbol)builder.CollectionType; if (collectionType.IsGenericType) { // If the type is generic, we have to search for the methods builder.ElementTypeWithAnnotations = collectionType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); MethodSymbol getEnumeratorMethod; if (isAsync) { Debug.Assert(IsIAsyncEnumerable(collectionType.OriginalDefinition)); getEnumeratorMethod = (MethodSymbol)GetWellKnownTypeMember(Compilation, WellKnownMember.System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator, diagnostics, errorLocationSyntax.Location, isOptional: false); // Well-known members are matched by signature: we shouldn't find it if it doesn't have exactly 1 parameter. Debug.Assert(getEnumeratorMethod is null or { ParameterCount: 1 }); if (getEnumeratorMethod?.Parameters[0].IsOptional == false) { // This indicates a problem with the well-known IAsyncEnumerable type - it should have an optional cancellation token. diagnostics.Add(ErrorCode.ERR_AwaitForEachMissingMember, _syntax.Expression.Location, unwrappedCollectionExprType, GetAsyncEnumeratorMethodName); return EnumeratorResult.FailedAndReported; } } else { Debug.Assert(collectionType.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T); getEnumeratorMethod = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Collections_Generic_IEnumerable_T__GetEnumerator, diagnostics, errorLocationSyntax); } MethodSymbol moveNextMethod = null; if ((object)getEnumeratorMethod != null) { MethodSymbol specificGetEnumeratorMethod = getEnumeratorMethod.AsMember(collectionType); TypeSymbol enumeratorType = specificGetEnumeratorMethod.ReturnType; // IAsyncEnumerable<T>.GetAsyncEnumerator has a default param, so let's fill it in builder.GetEnumeratorInfo = BindDefaultArguments( specificGetEnumeratorMethod, extensionReceiverOpt: null, expanded: false, collectionExpr.Syntax, diagnostics, // C# 8 shipped allowing the CancellationToken of `IAsyncEnumerable.GetAsyncEnumerator` to be non-optional, // filling in a default value in that case. https://github.com/dotnet/roslyn/issues/50182 tracks making // this an error and breaking the scenario. assertMissingParametersAreOptional: false); MethodSymbol currentPropertyGetter; if (isAsync) { Debug.Assert(enumeratorType.OriginalDefinition.Equals(Compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T))); MethodSymbol moveNextAsync = (MethodSymbol)GetWellKnownTypeMember(WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync, diagnostics, errorLocationSyntax.Location, isOptional: false); if ((object)moveNextAsync != null) { moveNextMethod = moveNextAsync.AsMember((NamedTypeSymbol)enumeratorType); } currentPropertyGetter = (MethodSymbol)GetWellKnownTypeMember(Compilation, WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__get_Current, diagnostics, errorLocationSyntax.Location, isOptional: false); } else { currentPropertyGetter = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Collections_Generic_IEnumerator_T__get_Current, diagnostics, errorLocationSyntax); } if ((object)currentPropertyGetter != null) { builder.CurrentPropertyGetter = currentPropertyGetter.AsMember((NamedTypeSymbol)enumeratorType); } } if (!isAsync) { // NOTE: MoveNext is actually inherited from System.Collections.IEnumerator moveNextMethod = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext, diagnostics, errorLocationSyntax); } // We're operating with well-known members: we know MoveNext/MoveNextAsync have no parameters if (moveNextMethod is not null) { builder.MoveNextInfo = MethodArgumentInfo.CreateParameterlessMethod(moveNextMethod); } } else { // Non-generic - use special members to avoid re-computing Debug.Assert(collectionType.SpecialType == SpecialType.System_Collections_IEnumerable); builder.GetEnumeratorInfo = GetParameterlessSpecialTypeMemberInfo(SpecialMember.System_Collections_IEnumerable__GetEnumerator, errorLocationSyntax, diagnostics); builder.CurrentPropertyGetter = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__get_Current, diagnostics, errorLocationSyntax); builder.MoveNextInfo = GetParameterlessSpecialTypeMemberInfo(SpecialMember.System_Collections_IEnumerator__MoveNext, errorLocationSyntax, diagnostics); builder.ElementTypeWithAnnotations = builder.CurrentPropertyGetter?.ReturnTypeWithAnnotations ?? TypeWithAnnotations.Create(GetSpecialType(SpecialType.System_Object, diagnostics, errorLocationSyntax)); Debug.Assert((object)builder.GetEnumeratorInfo == null || builder.GetEnumeratorInfo.Method.ReturnType.SpecialType == SpecialType.System_Collections_IEnumerator); } // We don't know the runtime type, so we will have to insert a runtime check for IDisposable (with a conditional call to IDisposable.Dispose). builder.NeedsDisposal = true; return EnumeratorResult.Succeeded; } private bool ReportConstantNullCollectionExpr(BoundExpression collectionExpr, BindingDiagnosticBag diagnostics) { if (collectionExpr.ConstantValue is { IsNull: true }) { // Spec seems to refer to null literals, but Dev10 reports anything known to be null. diagnostics.Add(ErrorCode.ERR_NullNotValid, _syntax.Expression.Location); return true; } return false; } private void GetDisposalInfoForEnumerator(ref ForEachEnumeratorInfo.Builder builder, BoundExpression expr, bool isAsync, BindingDiagnosticBag diagnostics) { // NOTE: if IDisposable is not available at all, no diagnostics will be reported - we will just assume that // the enumerator is not disposable. If it has IDisposable in its interface list, there will be a diagnostic there. // If IDisposable is available but its Dispose method is not, then diagnostics will be reported only if the enumerator // is potentially disposable. TypeSymbol enumeratorType = builder.GetEnumeratorInfo.Method.ReturnType; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // For async foreach, we don't do the runtime check if ((!enumeratorType.IsSealed && !isAsync) || this.Conversions.ClassifyImplicitConversionFromType(enumeratorType, isAsync ? this.Compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : this.Compilation.GetSpecialType(SpecialType.System_IDisposable), ref useSiteInfo).IsImplicit) { builder.NeedsDisposal = true; } else if (Compilation.IsFeatureEnabled(MessageID.IDS_FeatureUsingDeclarations) && (enumeratorType.IsRefLikeType || isAsync)) { // if it wasn't directly convertable to IDisposable, see if it is pattern-disposable // again, we throw away any binding diagnostics, and assume it's not disposable if we encounter errors var receiver = new BoundDisposableValuePlaceholder(_syntax, enumeratorType); MethodSymbol disposeMethod = TryFindDisposePatternMethod(receiver, _syntax, isAsync, BindingDiagnosticBag.Discarded); if (disposeMethod is object) { Debug.Assert(!disposeMethod.IsExtensionMethod); Debug.Assert(disposeMethod.ParameterRefKinds.IsDefaultOrEmpty); var argsBuilder = ArrayBuilder<BoundExpression>.GetInstance(disposeMethod.ParameterCount); var argsToParams = default(ImmutableArray<int>); bool expanded = disposeMethod.HasParamsParameter(); BindDefaultArguments( _syntax, disposeMethod.Parameters, argsBuilder, argumentRefKindsBuilder: null, ref argsToParams, out BitVector defaultArguments, expanded, enableCallerInfo: true, diagnostics); builder.NeedsDisposal = true; builder.PatternDisposeInfo = new MethodArgumentInfo(disposeMethod, argsBuilder.ToImmutableAndFree(), argsToParams, defaultArguments, expanded); } } diagnostics.Add(_syntax, useSiteInfo); } private ForEachEnumeratorInfo.Builder GetDefaultEnumeratorInfo(ForEachEnumeratorInfo.Builder builder, BindingDiagnosticBag diagnostics, TypeSymbol collectionExprType) { // NOTE: for arrays, we won't actually use any of these members - they're just for the API. builder.CollectionType = GetSpecialType(SpecialType.System_Collections_IEnumerable, diagnostics, _syntax); if (collectionExprType.IsDynamic()) { builder.ElementTypeWithAnnotations = TypeWithAnnotations.Create( ((_syntax as ForEachStatementSyntax)?.Type.IsVar == true) ? (TypeSymbol)DynamicTypeSymbol.Instance : GetSpecialType(SpecialType.System_Object, diagnostics, _syntax)); } else { builder.ElementTypeWithAnnotations = collectionExprType.SpecialType == SpecialType.System_String ? TypeWithAnnotations.Create(GetSpecialType(SpecialType.System_Char, diagnostics, _syntax)) : ((ArrayTypeSymbol)collectionExprType).ElementTypeWithAnnotations; } // CONSIDER: // For arrays and string none of these members will actually be emitted, so it seems strange to prevent compilation if they can't be found. // skip this work in the batch case? builder.GetEnumeratorInfo = GetParameterlessSpecialTypeMemberInfo(SpecialMember.System_Collections_IEnumerable__GetEnumerator, _syntax, diagnostics); builder.CurrentPropertyGetter = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__get_Current, diagnostics, _syntax); builder.MoveNextInfo = GetParameterlessSpecialTypeMemberInfo(SpecialMember.System_Collections_IEnumerator__MoveNext, _syntax, diagnostics); Debug.Assert((object)builder.GetEnumeratorInfo == null || TypeSymbol.Equals(builder.GetEnumeratorInfo.Method.ReturnType, this.Compilation.GetSpecialType(SpecialType.System_Collections_IEnumerator), TypeCompareKind.ConsiderEverything2)); // We don't know the runtime type, so we will have to insert a runtime check for IDisposable (with a conditional call to IDisposable.Dispose). builder.NeedsDisposal = true; return builder; } /// <summary> /// Check for a GetEnumerator (or GetAsyncEnumerator) method on collectionExprType. Failing to satisfy the pattern is not an error - /// it just means that we have to check for an interface instead. /// </summary> /// <param name="collectionExpr">Expression over which to iterate.</param> /// <param name="diagnostics">Populated with *warnings* if there are near misses.</param> /// <param name="builder">Builder to fill in. <see cref="ForEachEnumeratorInfo.Builder.GetEnumeratorInfo"/> set if the pattern in satisfied.</param> /// <returns>True if the method was found (still have to verify that the return (i.e. enumerator) type is acceptable).</returns> /// <remarks> /// Only adds warnings, so does not affect control flow (i.e. no need to check for failure). /// </remarks> private bool SatisfiesGetEnumeratorPattern(ref ForEachEnumeratorInfo.Builder builder, BoundExpression collectionExpr, bool isAsync, bool viaExtensionMethod, BindingDiagnosticBag diagnostics) { string methodName = isAsync ? GetAsyncEnumeratorMethodName : GetEnumeratorMethodName; MethodArgumentInfo getEnumeratorInfo; if (viaExtensionMethod) { getEnumeratorInfo = FindForEachPatternMethodViaExtension(collectionExpr, methodName, diagnostics); } else { var lookupResult = LookupResult.GetInstance(); getEnumeratorInfo = FindForEachPatternMethod(collectionExpr.Type, methodName, lookupResult, warningsOnly: true, diagnostics, isAsync); lookupResult.Free(); } builder.GetEnumeratorInfo = getEnumeratorInfo; return (object)getEnumeratorInfo != null; } /// <summary> /// Perform a lookup for the specified method on the specified type. Perform overload resolution /// on the lookup results. /// </summary> /// <param name="patternType">Type to search.</param> /// <param name="methodName">Method to search for.</param> /// <param name="lookupResult">Passed in for reusability.</param> /// <param name="warningsOnly">True if failures should result in warnings; false if they should result in errors.</param> /// <param name="diagnostics">Populated with binding diagnostics.</param> /// <returns>The desired method or null.</returns> private MethodArgumentInfo FindForEachPatternMethod(TypeSymbol patternType, string methodName, LookupResult lookupResult, bool warningsOnly, BindingDiagnosticBag diagnostics, bool isAsync) { Debug.Assert(lookupResult.IsClear); // Not using LookupOptions.MustBeInvocableMember because we don't want the corresponding lookup error. // We filter out non-methods below. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersInType( lookupResult, patternType, methodName, arity: 0, basesBeingResolved: null, options: LookupOptions.Default, originalBinder: this, diagnose: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(_syntax.Expression, useSiteInfo); if (!lookupResult.IsMultiViable) { ReportPatternMemberLookupDiagnostics(lookupResult, patternType, methodName, warningsOnly, diagnostics); return null; } ArrayBuilder<MethodSymbol> candidateMethods = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (Symbol member in lookupResult.Symbols) { if (member.Kind != SymbolKind.Method) { candidateMethods.Free(); if (warningsOnly) { ReportEnumerableWarning(diagnostics, patternType, member); } return null; } MethodSymbol method = (MethodSymbol)member; // SPEC VIOLATION: The spec says we should apply overload resolution, but Dev10 uses // some custom logic in ExpressionBinder.BindGrpToParams. The biggest difference // we've found (so far) is that it only considers methods with expected number of parameters // (i.e. doesn't work with "params" or optional parameters). // Note: for pattern-based lookup for `await foreach` we accept `GetAsyncEnumerator` and // `MoveNextAsync` methods with optional/params parameters. if (method.ParameterCount == 0 || isAsync) { candidateMethods.Add((MethodSymbol)member); } } MethodArgumentInfo patternInfo = PerformForEachPatternOverloadResolution(patternType, candidateMethods, warningsOnly, diagnostics, isAsync); candidateMethods.Free(); return patternInfo; } /// <summary> /// The overload resolution portion of FindForEachPatternMethod. /// If no arguments are passed in, then an empty argument list will be used. /// </summary> private MethodArgumentInfo PerformForEachPatternOverloadResolution(TypeSymbol patternType, ArrayBuilder<MethodSymbol> candidateMethods, bool warningsOnly, BindingDiagnosticBag diagnostics, bool isAsync) { var analyzedArguments = AnalyzedArguments.GetInstance(); var typeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // We create a dummy receiver of the invocation so MethodInvocationOverloadResolution knows it was invoked from an instance, not a type var dummyReceiver = new BoundImplicitReceiver(_syntax.Expression, patternType); this.OverloadResolution.MethodInvocationOverloadResolution( methods: candidateMethods, typeArguments: typeArguments, receiver: dummyReceiver, arguments: analyzedArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo); diagnostics.Add(_syntax.Expression, useSiteInfo); MethodSymbol result = null; MethodArgumentInfo info = null; if (overloadResolutionResult.Succeeded) { result = overloadResolutionResult.ValidResult.Member; if (result.IsStatic || result.DeclaredAccessibility != Accessibility.Public) { if (warningsOnly) { MessageID patternName = isAsync ? MessageID.IDS_FeatureAsyncStreams : MessageID.IDS_Collection; diagnostics.Add(ErrorCode.WRN_PatternNotPublicOrNotInstance, _syntax.Expression.Location, patternType, patternName.Localize(), result); } result = null; } else if (result.CallsAreOmitted(_syntax.SyntaxTree)) { // Calls to this method are omitted in the current syntax tree, i.e it is either a partial method with no implementation part OR a conditional method whose condition is not true in this source file. // We don't want to allow this case. result = null; } else { var argsToParams = overloadResolutionResult.ValidResult.Result.ArgsToParamsOpt; var expanded = overloadResolutionResult.ValidResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; BindDefaultArguments( _syntax, result.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out BitVector defaultArguments, expanded, enableCallerInfo: true, diagnostics); info = new MethodArgumentInfo(result, analyzedArguments.Arguments.ToImmutable(), argsToParams, defaultArguments, expanded); } } else if (overloadResolutionResult.GetAllApplicableMembers() is var applicableMembers && applicableMembers.Length > 1) { if (warningsOnly) { diagnostics.Add(ErrorCode.WRN_PatternIsAmbiguous, _syntax.Expression.Location, patternType, MessageID.IDS_Collection.Localize(), applicableMembers[0], applicableMembers[1]); } } overloadResolutionResult.Free(); analyzedArguments.Free(); typeArguments.Free(); return info; } private MethodArgumentInfo FindForEachPatternMethodViaExtension(BoundExpression collectionExpr, string methodName, BindingDiagnosticBag diagnostics) { var analyzedArguments = AnalyzedArguments.GetInstance(); var methodGroupResolutionResult = this.BindExtensionMethod( _syntax.Expression, methodName, analyzedArguments, collectionExpr, typeArgumentsWithAnnotations: default, isMethodGroupConversion: false, returnRefKind: default, returnType: null, withDependencies: diagnostics.AccumulatesDependencies); diagnostics.AddRange(methodGroupResolutionResult.Diagnostics); var overloadResolutionResult = methodGroupResolutionResult.OverloadResolutionResult; if (overloadResolutionResult?.Succeeded ?? false) { var result = overloadResolutionResult.ValidResult.Member; if (result.CallsAreOmitted(_syntax.SyntaxTree)) { // Calls to this method are omitted in the current syntax tree, i.e it is either a partial method with no implementation part OR a conditional method whose condition is not true in this source file. // We don't want to allow this case. methodGroupResolutionResult.Free(); analyzedArguments.Free(); return null; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var collectionConversion = this.Conversions.ClassifyConversionFromExpression(collectionExpr, result.Parameters[0].Type, ref useSiteInfo); diagnostics.Add(_syntax, useSiteInfo); // Unconditionally convert here, to match what we set the ConvertedExpression to in the main BoundForEachStatement node. Debug.Assert(!collectionConversion.IsUserDefined); collectionExpr = new BoundConversion( collectionExpr.Syntax, collectionExpr, collectionConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, result.Parameters[0].Type); var info = BindDefaultArguments( result, collectionExpr, expanded: overloadResolutionResult.ValidResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm, collectionExpr.Syntax, diagnostics); methodGroupResolutionResult.Free(); analyzedArguments.Free(); return info; } else if (overloadResolutionResult?.GetAllApplicableMembers() is { } applicableMembers && applicableMembers.Length > 1) { diagnostics.Add(ErrorCode.WRN_PatternIsAmbiguous, _syntax.Expression.Location, collectionExpr.Type, MessageID.IDS_Collection.Localize(), applicableMembers[0], applicableMembers[1]); } else if (overloadResolutionResult != null) { overloadResolutionResult.ReportDiagnostics( binder: this, location: _syntax.Expression.Location, nodeOpt: _syntax.Expression, diagnostics: diagnostics, name: methodName, receiver: null, invokedExpression: _syntax.Expression, arguments: methodGroupResolutionResult.AnalyzedArguments, memberGroup: methodGroupResolutionResult.MethodGroup.Methods.ToImmutable(), typeContainingConstructor: null, delegateTypeBeingInvoked: null); } methodGroupResolutionResult.Free(); analyzedArguments.Free(); return null; } /// <summary> /// Called after it is determined that the expression being enumerated is of a type that /// has a GetEnumerator (or GetAsyncEnumerator) method. Checks to see if the return type of the GetEnumerator /// method is suitable (i.e. has Current and MoveNext for regular case, /// or Current and MoveNextAsync for async case). /// </summary> /// <param name="builder">Must be non-null and contain a non-null GetEnumeratorMethod.</param> /// <param name="diagnostics">Will be populated with pattern diagnostics.</param> /// <returns>True if the return type has suitable members.</returns> /// <remarks> /// It seems that every failure path reports the same diagnostics, so that is left to the caller. /// </remarks> private bool SatisfiesForEachPattern(ref ForEachEnumeratorInfo.Builder builder, bool isAsync, BindingDiagnosticBag diagnostics) { Debug.Assert((object)builder.GetEnumeratorInfo.Method != null); MethodSymbol getEnumeratorMethod = builder.GetEnumeratorInfo.Method; TypeSymbol enumeratorType = getEnumeratorMethod.ReturnType; switch (enumeratorType.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.TypeParameter: // Not specifically mentioned in the spec, but consistent with Dev10. case TypeKind.Dynamic: // Not specifically mentioned in the spec, but consistent with Dev10. break; case TypeKind.Submission: // submission class is synthesized and should never appear in a foreach: throw ExceptionUtilities.UnexpectedValue(enumeratorType.TypeKind); default: return false; } // Use a try-finally since there are many return points LookupResult lookupResult = LookupResult.GetInstance(); try { // If we searched for the accessor directly, we could reuse FindForEachPatternMethod and we // wouldn't have to mangle CurrentPropertyName. However, Dev10 searches for the property and // then extracts the accessor, so we should do the same (in case of accessors with non-standard // names). CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersInType( lookupResult, enumeratorType, CurrentPropertyName, arity: 0, basesBeingResolved: null, options: LookupOptions.Default, // properties are not invocable - their accessors are originalBinder: this, diagnose: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(_syntax.Expression, useSiteInfo); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); if (!lookupResult.IsSingleViable) { ReportPatternMemberLookupDiagnostics(lookupResult, enumeratorType, CurrentPropertyName, warningsOnly: false, diagnostics: diagnostics); return false; } // lookupResult.IsSingleViable above guaranteed there is exactly one symbol. Symbol lookupSymbol = lookupResult.SingleSymbolOrDefault; Debug.Assert((object)lookupSymbol != null); if (lookupSymbol.IsStatic || lookupSymbol.DeclaredAccessibility != Accessibility.Public || lookupSymbol.Kind != SymbolKind.Property) { return false; } // NOTE: accessor can be inherited from overridden property MethodSymbol currentPropertyGetterCandidate = ((PropertySymbol)lookupSymbol).GetOwnOrInheritedGetMethod(); if ((object)currentPropertyGetterCandidate == null) { return false; } else { bool isAccessible = this.IsAccessible(currentPropertyGetterCandidate, ref useSiteInfo); diagnostics.Add(_syntax.Expression, useSiteInfo); if (!isAccessible) { // NOTE: per Dev10 and the spec, the property has to be public, but the accessor just has to be accessible return false; } } builder.CurrentPropertyGetter = currentPropertyGetterCandidate; lookupResult.Clear(); // Reuse the same LookupResult MethodArgumentInfo moveNextMethodCandidate = FindForEachPatternMethod(enumeratorType, isAsync ? MoveNextAsyncMethodName : MoveNextMethodName, lookupResult, warningsOnly: false, diagnostics, isAsync); if ((object)moveNextMethodCandidate == null || moveNextMethodCandidate.Method.IsStatic || moveNextMethodCandidate.Method.DeclaredAccessibility != Accessibility.Public || IsInvalidMoveNextMethod(moveNextMethodCandidate.Method, isAsync)) { return false; } builder.MoveNextInfo = moveNextMethodCandidate; return true; } finally { lookupResult.Free(); } } private bool IsInvalidMoveNextMethod(MethodSymbol moveNextMethodCandidate, bool isAsync) { if (isAsync) { // We'll verify the return type from `MoveNextAsync` when we try to bind the `await` for it return false; } // SPEC VIOLATION: Dev10 checks the return type of the original definition, rather than the return type of the actual method. return moveNextMethodCandidate.OriginalDefinition.ReturnType.SpecialType != SpecialType.System_Boolean; } private void ReportEnumerableWarning(BindingDiagnosticBag diagnostics, TypeSymbol enumeratorType, Symbol patternMemberCandidate) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (this.IsAccessible(patternMemberCandidate, ref useSiteInfo)) { diagnostics.Add(ErrorCode.WRN_PatternBadSignature, _syntax.Expression.Location, enumeratorType, MessageID.IDS_Collection.Localize(), patternMemberCandidate); } diagnostics.Add(_syntax.Expression, useSiteInfo); } private static bool IsIEnumerable(TypeSymbol type) { switch (((TypeSymbol)type.OriginalDefinition).SpecialType) { case SpecialType.System_Collections_IEnumerable: case SpecialType.System_Collections_Generic_IEnumerable_T: return true; default: return false; } } private bool IsIAsyncEnumerable(TypeSymbol type) { return type.OriginalDefinition.Equals(Compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T)); } /// <summary> /// Checks if the given type implements (or extends, in the case of an interface), /// System.Collections.IEnumerable or System.Collections.Generic.IEnumerable&lt;T&gt;, /// (or System.Collections.Generic.IAsyncEnumerable&lt;T&gt;) /// for at least one T. /// </summary> /// <param name="builder">builder to fill in CollectionType.</param> /// <param name="type">Type to check.</param> /// <param name="diagnostics" /> /// <param name="foundMultiple">True if multiple T's are found.</param> /// <returns>True if some IEnumerable is found (may still be ambiguous).</returns> private bool AllInterfacesContainsIEnumerable( ref ForEachEnumeratorInfo.Builder builder, TypeSymbol type, bool isAsync, BindingDiagnosticBag diagnostics, out bool foundMultiple) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); NamedTypeSymbol implementedIEnumerable = GetIEnumerableOfT(type, isAsync, Compilation, ref useSiteInfo, out foundMultiple); // Prefer generic to non-generic, unless it is inaccessible. if (((object)implementedIEnumerable == null) || !this.IsAccessible(implementedIEnumerable, ref useSiteInfo)) { implementedIEnumerable = null; if (!isAsync) { var implementedNonGeneric = this.Compilation.GetSpecialType(SpecialType.System_Collections_IEnumerable); if ((object)implementedNonGeneric != null) { var conversion = this.Conversions.ClassifyImplicitConversionFromType(type, implementedNonGeneric, ref useSiteInfo); if (conversion.IsImplicit) { implementedIEnumerable = implementedNonGeneric; } } } } diagnostics.Add(_syntax.Expression, useSiteInfo); builder.CollectionType = implementedIEnumerable; return (object)implementedIEnumerable != null; } internal static NamedTypeSymbol GetIEnumerableOfT(TypeSymbol type, bool isAsync, CSharpCompilation compilation, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool foundMultiple) { NamedTypeSymbol implementedIEnumerable = null; foundMultiple = false; if (type.TypeKind == TypeKind.TypeParameter) { var typeParameter = (TypeParameterSymbol)type; var allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo) .Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); GetIEnumerableOfT(allInterfaces, isAsync, compilation, ref @implementedIEnumerable, ref foundMultiple); } else { GetIEnumerableOfT(type.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo), isAsync, compilation, ref @implementedIEnumerable, ref foundMultiple); } return implementedIEnumerable; } private static void GetIEnumerableOfT(ImmutableArray<NamedTypeSymbol> interfaces, bool isAsync, CSharpCompilation compilation, ref NamedTypeSymbol result, ref bool foundMultiple) { if (foundMultiple) { return; } interfaces = MethodTypeInferrer.ModuloReferenceTypeNullabilityDifferences(interfaces, VarianceKind.In); foreach (NamedTypeSymbol @interface in interfaces) { if (IsIEnumerableT(@interface.OriginalDefinition, isAsync, compilation)) { if ((object)result == null || TypeSymbol.Equals(@interface, result, TypeCompareKind.IgnoreTupleNames)) { result = @interface; } else { foundMultiple = true; return; } } } } internal static bool IsIEnumerableT(TypeSymbol type, bool isAsync, CSharpCompilation compilation) { if (isAsync) { return type.Equals(compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T)); } else { return type.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T; } } /// <summary> /// Report appropriate diagnostics when lookup of a pattern member (i.e. GetEnumerator, Current, or MoveNext) fails. /// </summary> /// <param name="lookupResult">Failed lookup result.</param> /// <param name="patternType">Type in which member was looked up.</param> /// <param name="memberName">Name of looked up member.</param> /// <param name="warningsOnly">True if failures should result in warnings; false if they should result in errors.</param> /// <param name="diagnostics">Populated appropriately.</param> private void ReportPatternMemberLookupDiagnostics(LookupResult lookupResult, TypeSymbol patternType, string memberName, bool warningsOnly, BindingDiagnosticBag diagnostics) { if (lookupResult.Symbols.Any()) { if (warningsOnly) { ReportEnumerableWarning(diagnostics, patternType, lookupResult.Symbols.First()); } else { lookupResult.Clear(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersInType( lookupResult, patternType, memberName, arity: 0, basesBeingResolved: null, options: LookupOptions.Default, originalBinder: this, diagnose: true, useSiteInfo: ref useSiteInfo); diagnostics.Add(_syntax.Expression, useSiteInfo); if (lookupResult.Error != null) { diagnostics.Add(lookupResult.Error, _syntax.Expression.Location); } } } else if (!warningsOnly) { diagnostics.Add(ErrorCode.ERR_NoSuchMember, _syntax.Expression.Location, patternType, memberName); } } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (_syntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _syntax; } } private MethodArgumentInfo GetParameterlessSpecialTypeMemberInfo(SpecialMember member, SyntaxNode syntax, BindingDiagnosticBag diagnostics) { var resolvedMember = (MethodSymbol)GetSpecialTypeMember(member, diagnostics, syntax); Debug.Assert(resolvedMember is null or { ParameterCount: 0 }); return resolvedMember is not null ? MethodArgumentInfo.CreateParameterlessMethod(resolvedMember) : null; } /// <param name="extensionReceiverOpt">If method is an extension method, this must be non-null.</param> private MethodArgumentInfo BindDefaultArguments(MethodSymbol method, BoundExpression extensionReceiverOpt, bool expanded, SyntaxNode syntax, BindingDiagnosticBag diagnostics, bool assertMissingParametersAreOptional = true) { Debug.Assert((extensionReceiverOpt != null) == method.IsExtensionMethod); if (method.ParameterCount == 0) { return MethodArgumentInfo.CreateParameterlessMethod(method); } var argsBuilder = ArrayBuilder<BoundExpression>.GetInstance(method.ParameterCount); if (method.IsExtensionMethod) { argsBuilder.Add(extensionReceiverOpt); } ImmutableArray<int> argsToParams = default; BindDefaultArguments( syntax, method.Parameters, argsBuilder, argumentRefKindsBuilder: null, ref argsToParams, defaultArguments: out BitVector defaultArguments, expanded, enableCallerInfo: true, diagnostics, assertMissingParametersAreOptional); return new MethodArgumentInfo(method, argsBuilder.ToImmutableAndFree(), argsToParams, defaultArguments, expanded); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A loop binder that (1) knows how to bind foreach loops and (2) has the foreach iteration variable in scope. /// </summary> /// <remarks> /// This binder produces BoundForEachStatements. The lowering described in the spec is performed in ControlFlowRewriter. /// </remarks> internal sealed class ForEachLoopBinder : LoopBinder { private const string GetEnumeratorMethodName = WellKnownMemberNames.GetEnumeratorMethodName; private const string CurrentPropertyName = WellKnownMemberNames.CurrentPropertyName; private const string MoveNextMethodName = WellKnownMemberNames.MoveNextMethodName; private const string GetAsyncEnumeratorMethodName = WellKnownMemberNames.GetAsyncEnumeratorMethodName; private const string MoveNextAsyncMethodName = WellKnownMemberNames.MoveNextAsyncMethodName; private readonly CommonForEachStatementSyntax _syntax; private SourceLocalSymbol IterationVariable { get { return (_syntax.Kind() == SyntaxKind.ForEachStatement) ? (SourceLocalSymbol)this.Locals[0] : null; } } private bool IsAsync => _syntax.AwaitKeyword != default; public ForEachLoopBinder(Binder enclosing, CommonForEachStatementSyntax syntax) : base(enclosing) { Debug.Assert(syntax != null); _syntax = syntax; } protected override ImmutableArray<LocalSymbol> BuildLocals() { switch (_syntax.Kind()) { case SyntaxKind.ForEachVariableStatement: { var syntax = (ForEachVariableStatementSyntax)_syntax; var locals = ArrayBuilder<LocalSymbol>.GetInstance(); CollectLocalsFromDeconstruction( syntax.Variable, LocalDeclarationKind.ForEachIterationVariable, locals, syntax); return locals.ToImmutableAndFree(); } case SyntaxKind.ForEachStatement: { var syntax = (ForEachStatementSyntax)_syntax; var iterationVariable = SourceLocalSymbol.MakeForeachLocal( (MethodSymbol)this.ContainingMemberOrLambda, this, syntax.Type, syntax.Identifier, syntax.Expression); return ImmutableArray.Create<LocalSymbol>(iterationVariable); } default: throw ExceptionUtilities.UnexpectedValue(_syntax.Kind()); } } internal void CollectLocalsFromDeconstruction( ExpressionSyntax declaration, LocalDeclarationKind kind, ArrayBuilder<LocalSymbol> locals, SyntaxNode deconstructionStatement, Binder enclosingBinderOpt = null) { switch (declaration.Kind()) { case SyntaxKind.TupleExpression: { var tuple = (TupleExpressionSyntax)declaration; foreach (var arg in tuple.Arguments) { CollectLocalsFromDeconstruction(arg.Expression, kind, locals, deconstructionStatement, enclosingBinderOpt); } break; } case SyntaxKind.DeclarationExpression: { var declarationExpression = (DeclarationExpressionSyntax)declaration; CollectLocalsFromDeconstruction( declarationExpression.Designation, declarationExpression.Type, kind, locals, deconstructionStatement, enclosingBinderOpt); break; } case SyntaxKind.IdentifierName: break; default: // In broken code, we can have an arbitrary expression here. Collect its expression variables. ExpressionVariableFinder.FindExpressionVariables(this, locals, declaration); break; } } internal void CollectLocalsFromDeconstruction( VariableDesignationSyntax designation, TypeSyntax closestTypeSyntax, LocalDeclarationKind kind, ArrayBuilder<LocalSymbol> locals, SyntaxNode deconstructionStatement, Binder enclosingBinderOpt) { switch (designation.Kind()) { case SyntaxKind.SingleVariableDesignation: { var single = (SingleVariableDesignationSyntax)designation; SourceLocalSymbol localSymbol = SourceLocalSymbol.MakeDeconstructionLocal( this.ContainingMemberOrLambda, this, enclosingBinderOpt ?? this, closestTypeSyntax, single.Identifier, kind, deconstructionStatement); locals.Add(localSymbol); break; } case SyntaxKind.ParenthesizedVariableDesignation: { var tuple = (ParenthesizedVariableDesignationSyntax)designation; foreach (var d in tuple.Variables) { CollectLocalsFromDeconstruction(d, closestTypeSyntax, kind, locals, deconstructionStatement, enclosingBinderOpt); } break; } case SyntaxKind.DiscardDesignation: break; default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } /// <summary> /// Bind the ForEachStatementSyntax at the root of this binder. /// </summary> internal override BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { BoundForEachStatement result = BindForEachPartsWorker(diagnostics, originalBinder); return result; } /// <summary> /// Like BindForEachParts, but only bind the deconstruction part of the foreach, for purpose of inferring the types of the declared locals. /// </summary> internal override BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) { // Use the right binder to avoid seeing iteration variable BoundExpression collectionExpr = originalBinder.GetBinder(_syntax.Expression).BindRValueWithoutTargetType(_syntax.Expression, diagnostics); var builder = new ForEachEnumeratorInfo.Builder(); TypeWithAnnotations inferredType; bool hasErrors = !GetEnumeratorInfoAndInferCollectionElementType(ref builder, ref collectionExpr, diagnostics, out inferredType); ExpressionSyntax variables = ((ForEachVariableStatementSyntax)_syntax).Variable; // Tracking narrowest safe-to-escape scope by default, the proper val escape will be set when doing full binding of the foreach statement var valuePlaceholder = new BoundDeconstructValuePlaceholder(_syntax.Expression, this.LocalScopeDepth, inferredType.Type ?? CreateErrorType("var")); DeclarationExpressionSyntax declaration = null; ExpressionSyntax expression = null; BoundDeconstructionAssignmentOperator deconstruction = BindDeconstruction( variables, variables, right: _syntax.Expression, diagnostics: diagnostics, rightPlaceholder: valuePlaceholder, declaration: ref declaration, expression: ref expression); return new BoundExpressionStatement(_syntax, deconstruction); } private BoundForEachStatement BindForEachPartsWorker(BindingDiagnosticBag diagnostics, Binder originalBinder) { // Use the right binder to avoid seeing iteration variable BoundExpression collectionExpr = originalBinder.GetBinder(_syntax.Expression).BindRValueWithoutTargetType(_syntax.Expression, diagnostics); var builder = new ForEachEnumeratorInfo.Builder(); TypeWithAnnotations inferredType; bool hasErrors = !GetEnumeratorInfoAndInferCollectionElementType(ref builder, ref collectionExpr, diagnostics, out inferredType); // These occur when special types are missing or malformed, or the patterns are incompletely implemented. hasErrors |= builder.IsIncomplete; BoundAwaitableInfo awaitInfo = null; MethodSymbol getEnumeratorMethod = builder.GetEnumeratorInfo?.Method; if (getEnumeratorMethod != null) { originalBinder.CheckImplicitThisCopyInReadOnlyMember(collectionExpr, getEnumeratorMethod, diagnostics); if (getEnumeratorMethod.IsExtensionMethod && !hasErrors) { var messageId = IsAsync ? MessageID.IDS_FeatureExtensionGetAsyncEnumerator : MessageID.IDS_FeatureExtensionGetEnumerator; hasErrors |= !messageId.CheckFeatureAvailability( diagnostics, Compilation, collectionExpr.Syntax.Location); if (getEnumeratorMethod.ParameterRefKinds is { IsDefault: false } refKinds && refKinds[0] == RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_RefLvalueExpected, collectionExpr.Syntax); hasErrors = true; } } } if (IsAsync) { var expr = _syntax.Expression; ReportBadAwaitDiagnostics(expr, _syntax.AwaitKeyword.GetLocation(), diagnostics, ref hasErrors); var placeholder = new BoundAwaitableValuePlaceholder(expr, valEscape: this.LocalScopeDepth, builder.MoveNextInfo?.Method.ReturnType ?? CreateErrorType()); awaitInfo = BindAwaitInfo(placeholder, expr, diagnostics, ref hasErrors); if (!hasErrors && awaitInfo.GetResult?.ReturnType.SpecialType != SpecialType.System_Boolean) { diagnostics.Add(ErrorCode.ERR_BadGetAsyncEnumerator, expr.Location, getEnumeratorMethod.ReturnTypeWithAnnotations, getEnumeratorMethod); hasErrors = true; } } TypeWithAnnotations iterationVariableType; BoundTypeExpression boundIterationVariableType; bool hasNameConflicts = false; BoundForEachDeconstructStep deconstructStep = null; BoundExpression iterationErrorExpression = null; uint collectionEscape = GetValEscape(collectionExpr, this.LocalScopeDepth); switch (_syntax.Kind()) { case SyntaxKind.ForEachStatement: { var node = (ForEachStatementSyntax)_syntax; // Check for local variable conflicts in the *enclosing* binder; obviously the *current* // binder has a local that matches! hasNameConflicts = originalBinder.ValidateDeclarationNameConflictsInScope(IterationVariable, diagnostics); // If the type in syntax is "var", then the type should be set explicitly so that the // Type property doesn't fail. TypeSyntax typeSyntax = node.Type.SkipRef(out _); bool isVar; AliasSymbol alias; TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar, out alias); if (isVar) { declType = inferredType.HasType ? inferredType : TypeWithAnnotations.Create(CreateErrorType("var")); } else { Debug.Assert(declType.HasType); } iterationVariableType = declType; boundIterationVariableType = new BoundTypeExpression(typeSyntax, alias, iterationVariableType); SourceLocalSymbol local = this.IterationVariable; local.SetTypeWithAnnotations(declType); local.SetValEscape(collectionEscape); if (local.RefKind != RefKind.None) { // The ref-escape of a ref-returning property is decided // by the value escape of its receiver, in this case the // collection local.SetRefEscape(collectionEscape); if (CheckRefLocalInAsyncOrIteratorMethod(local.IdentifierToken, diagnostics)) { hasErrors = true; } } if (!hasErrors) { BindValueKind requiredCurrentKind; switch (local.RefKind) { case RefKind.None: requiredCurrentKind = BindValueKind.RValue; break; case RefKind.Ref: requiredCurrentKind = BindValueKind.Assignable | BindValueKind.RefersToLocation; break; case RefKind.RefReadOnly: requiredCurrentKind = BindValueKind.RefersToLocation; break; default: throw ExceptionUtilities.UnexpectedValue(local.RefKind); } hasErrors |= !CheckMethodReturnValueKind( builder.CurrentPropertyGetter, callSyntaxOpt: null, collectionExpr.Syntax, requiredCurrentKind, checkingReceiver: false, diagnostics); } break; } case SyntaxKind.ForEachVariableStatement: { var node = (ForEachVariableStatementSyntax)_syntax; iterationVariableType = inferredType.HasType ? inferredType : TypeWithAnnotations.Create(CreateErrorType("var")); var variables = node.Variable; if (variables.IsDeconstructionLeft()) { var valuePlaceholder = new BoundDeconstructValuePlaceholder(_syntax.Expression, collectionEscape, iterationVariableType.Type).MakeCompilerGenerated(); DeclarationExpressionSyntax declaration = null; ExpressionSyntax expression = null; BoundDeconstructionAssignmentOperator deconstruction = BindDeconstruction( variables, variables, right: _syntax.Expression, diagnostics: diagnostics, rightPlaceholder: valuePlaceholder, declaration: ref declaration, expression: ref expression); if (expression != null) { // error: must declare foreach loop iteration variables. Error(diagnostics, ErrorCode.ERR_MustDeclareForeachIteration, variables); hasErrors = true; } deconstructStep = new BoundForEachDeconstructStep(variables, deconstruction, valuePlaceholder).MakeCompilerGenerated(); } else { // Bind the expression for error recovery, but discard all new diagnostics iterationErrorExpression = BindExpression(node.Variable, BindingDiagnosticBag.Discarded); if (iterationErrorExpression.Kind == BoundKind.DiscardExpression) { iterationErrorExpression = ((BoundDiscardExpression)iterationErrorExpression).FailInference(this, diagnosticsOpt: null); } hasErrors = true; if (!node.HasErrors) { Error(diagnostics, ErrorCode.ERR_MustDeclareForeachIteration, variables); } } boundIterationVariableType = new BoundTypeExpression(variables, aliasOpt: null, typeWithAnnotations: iterationVariableType).MakeCompilerGenerated(); break; } default: throw ExceptionUtilities.UnexpectedValue(_syntax.Kind()); } BoundStatement body = originalBinder.BindPossibleEmbeddedStatement(_syntax.Statement, diagnostics); // NOTE: in error cases, binder may collect all kind of variables, not just formally declared iteration variables. // As a matter of error recovery, we will treat such variables the same as the iteration variables. // I.E. - they will be considered declared and assigned in each iteration step. ImmutableArray<LocalSymbol> iterationVariables = this.Locals; Debug.Assert(hasErrors || _syntax.HasErrors || iterationVariables.All(local => local.DeclarationKind == LocalDeclarationKind.ForEachIterationVariable), "Should not have iteration variables that are not ForEachIterationVariable in valid code"); hasErrors = hasErrors || boundIterationVariableType.HasErrors || iterationVariableType.Type.IsErrorType(); // Skip the conversion checks and array/enumerator differentiation if we know we have an error (except local name conflicts). if (hasErrors) { return new BoundForEachStatement( _syntax, enumeratorInfoOpt: null, // can't be sure that it's complete elementConversion: default, boundIterationVariableType, iterationVariables, iterationErrorExpression, collectionExpr, deconstructStep, awaitInfo, body, CheckOverflowAtRuntime, this.BreakLabel, this.ContinueLabel, hasErrors); } hasErrors |= hasNameConflicts; var foreachKeyword = _syntax.ForEachKeyword; ReportDiagnosticsIfObsolete(diagnostics, getEnumeratorMethod, foreachKeyword, hasBaseReceiver: false); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, getEnumeratorMethod, foreachKeyword.GetLocation(), isDelegateConversion: false); // MoveNext is an instance method, so it does not need to have unmanaged callers only diagnostics reported. // Either a diagnostic was reported at the declaration of the method (for the invalid attribute), or MoveNext // is marked as not supported and we won't get here in the first place (for metadata import). ReportDiagnosticsIfObsolete(diagnostics, builder.MoveNextInfo.Method, foreachKeyword, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter, foreachKeyword, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter.AssociatedSymbol, foreachKeyword, hasBaseReceiver: false); // We want to convert from inferredType in the array/string case and builder.ElementType in the enumerator case, // but it turns out that these are equivalent (when both are available). CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion elementConversion = this.Conversions.ClassifyConversionFromType(inferredType.Type, iterationVariableType.Type, ref useSiteInfo, forCast: true); if (!elementConversion.IsValid) { ImmutableArray<MethodSymbol> originalUserDefinedConversions = elementConversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { diagnostics.Add(ErrorCode.ERR_AmbigUDConv, foreachKeyword.GetLocation(), originalUserDefinedConversions[0], originalUserDefinedConversions[1], inferredType.Type, iterationVariableType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, inferredType.Type, iterationVariableType.Type); diagnostics.Add(ErrorCode.ERR_NoExplicitConv, foreachKeyword.GetLocation(), distinguisher.First, distinguisher.Second); } hasErrors = true; } else { ReportDiagnosticsIfObsolete(diagnostics, elementConversion, _syntax.ForEachKeyword, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(_syntax.ForEachKeyword, elementConversion, diagnostics); } // Spec (§8.8.4): // If the type X of expression is dynamic then there is an implicit conversion from >>expression<< (not the type of the expression) // to the System.Collections.IEnumerable interface (§6.1.8). builder.CollectionConversion = this.Conversions.ClassifyConversionFromExpression(collectionExpr, builder.CollectionType, ref useSiteInfo); builder.CurrentConversion = this.Conversions.ClassifyConversionFromType(builder.CurrentPropertyGetter.ReturnType, builder.ElementType, ref useSiteInfo); TypeSymbol getEnumeratorType = getEnumeratorMethod.ReturnType; // we never convert struct enumerators to object - it is done only for null-checks. builder.EnumeratorConversion = getEnumeratorType.IsValueType ? Conversion.Identity : this.Conversions.ClassifyConversionFromType(getEnumeratorType, GetSpecialType(SpecialType.System_Object, diagnostics, _syntax), ref useSiteInfo); if (getEnumeratorType.IsRestrictedType() && (IsDirectlyInIterator || IsInAsyncMethod())) { diagnostics.Add(ErrorCode.ERR_BadSpecialByRefIterator, foreachKeyword.GetLocation(), getEnumeratorType); } diagnostics.Add(_syntax.ForEachKeyword.GetLocation(), useSiteInfo); // Due to the way we extracted the various types, these conversions should always be possible. // CAVEAT: if we're iterating over an array of pointers, the current conversion will fail since we // can't convert from object to a pointer type. Similarly, if we're iterating over an array of // Nullable<Error>, the current conversion will fail because we don't know if an ErrorType is a // value type. This doesn't matter in practice, since we won't actually use the enumerator pattern // when we lower the loop. Debug.Assert(builder.CollectionConversion.IsValid); Debug.Assert(builder.CurrentConversion.IsValid || (builder.ElementType.IsPointerOrFunctionPointer() && collectionExpr.Type.IsArray()) || (builder.ElementType.IsNullableType() && builder.ElementType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single().IsErrorType() && collectionExpr.Type.IsArray())); Debug.Assert(builder.EnumeratorConversion.IsValid || this.Compilation.GetSpecialType(SpecialType.System_Object).TypeKind == TypeKind.Error || !useSiteInfo.Diagnostics.IsNullOrEmpty(), "Conversions to object succeed unless there's a problem with the object type or the source type"); // If user-defined conversions could occur here, we would need to check for ObsoleteAttribute. Debug.Assert((object)builder.CollectionConversion.Method == null, "Conversion from collection expression to collection type should not be user-defined"); Debug.Assert((object)builder.CurrentConversion.Method == null, "Conversion from Current property type to element type should not be user-defined"); Debug.Assert((object)builder.EnumeratorConversion.Method == null, "Conversion from GetEnumerator return type to System.Object should not be user-defined"); // We're wrapping the collection expression in a (non-synthesized) conversion so that its converted // type (i.e. builder.CollectionType) will be available in the binding API. Debug.Assert(!builder.CollectionConversion.IsUserDefined); BoundConversion convertedCollectionExpression = new BoundConversion( collectionExpr.Syntax, collectionExpr, builder.CollectionConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, builder.CollectionType); if (builder.NeedsDisposal && IsAsync) { hasErrors |= GetAwaitDisposeAsyncInfo(ref builder, diagnostics); } Debug.Assert( hasErrors || builder.CollectionConversion.IsIdentity || (builder.CollectionConversion.IsImplicit && (IsIEnumerable(builder.CollectionType) || IsIEnumerableT(builder.CollectionType.OriginalDefinition, IsAsync, Compilation) || builder.GetEnumeratorInfo.Method.IsExtensionMethod)) || // For compat behavior, we can enumerate over System.String even if it's not IEnumerable. That will // result in an explicit reference conversion in the bound nodes, but that conversion won't be emitted. (builder.CollectionConversion.Kind == ConversionKind.ExplicitReference && collectionExpr.Type.SpecialType == SpecialType.System_String)); return new BoundForEachStatement( _syntax, builder.Build(this.Flags), elementConversion, boundIterationVariableType, iterationVariables, iterationErrorExpression, convertedCollectionExpression, deconstructStep, awaitInfo, body, CheckOverflowAtRuntime, this.BreakLabel, this.ContinueLabel, hasErrors); } private bool GetAwaitDisposeAsyncInfo(ref ForEachEnumeratorInfo.Builder builder, BindingDiagnosticBag diagnostics) { var awaitableType = builder.PatternDisposeInfo is null ? this.GetWellKnownType(WellKnownType.System_Threading_Tasks_ValueTask, diagnostics, this._syntax) : builder.PatternDisposeInfo.Method.ReturnType; bool hasErrors = false; var expr = _syntax.Expression; ReportBadAwaitDiagnostics(expr, _syntax.AwaitKeyword.GetLocation(), diagnostics, ref hasErrors); var placeholder = new BoundAwaitableValuePlaceholder(expr, valEscape: this.LocalScopeDepth, awaitableType); builder.DisposeAwaitableInfo = BindAwaitInfo(placeholder, expr, diagnostics, ref hasErrors); return hasErrors; } internal TypeWithAnnotations InferCollectionElementType(BindingDiagnosticBag diagnostics, ExpressionSyntax collectionSyntax) { // Use the right binder to avoid seeing iteration variable BoundExpression collectionExpr = this.GetBinder(collectionSyntax).BindValue(collectionSyntax, diagnostics, BindValueKind.RValue); var builder = new ForEachEnumeratorInfo.Builder(); GetEnumeratorInfoAndInferCollectionElementType(ref builder, ref collectionExpr, diagnostics, out TypeWithAnnotations inferredType); return inferredType; } private bool GetEnumeratorInfoAndInferCollectionElementType(ref ForEachEnumeratorInfo.Builder builder, ref BoundExpression collectionExpr, BindingDiagnosticBag diagnostics, out TypeWithAnnotations inferredType) { bool gotInfo = GetEnumeratorInfo(ref builder, ref collectionExpr, diagnostics); if (!gotInfo) { inferredType = default; } else if (collectionExpr.HasDynamicType()) { // If the enumerator is dynamic, it yields dynamic values inferredType = TypeWithAnnotations.Create(DynamicTypeSymbol.Instance); } else if (collectionExpr.Type.SpecialType == SpecialType.System_String && builder.CollectionType.SpecialType == SpecialType.System_Collections_IEnumerable) { // Reproduce dev11 behavior: we're always going to lower a foreach loop over a string to a for loop // over the string's Chars indexer. Therefore, we should infer "char", regardless of what the spec // indicates the element type is. This actually matters in practice because the System.String in // the portable library doesn't have a pattern GetEnumerator method or implement IEnumerable<char>. inferredType = TypeWithAnnotations.Create(GetSpecialType(SpecialType.System_Char, diagnostics, collectionExpr.Syntax)); } else { inferredType = builder.ElementTypeWithAnnotations; } return gotInfo; } private BoundExpression UnwrapCollectionExpressionIfNullable(BoundExpression collectionExpr, BindingDiagnosticBag diagnostics) { TypeSymbol collectionExprType = collectionExpr.Type; // If collectionExprType is a nullable type, then use the underlying type and take the value (i.e. .Value) of collectionExpr. // This behavior is not spec'd, but it's what Dev10 does. if ((object)collectionExprType != null && collectionExprType.IsNullableType()) { SyntaxNode exprSyntax = collectionExpr.Syntax; MethodSymbol nullableValueGetter = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Nullable_T_get_Value, diagnostics, exprSyntax); if ((object)nullableValueGetter != null) { nullableValueGetter = nullableValueGetter.AsMember((NamedTypeSymbol)collectionExprType); // Synthesized call, because we don't want to modify the type in the SemanticModel. return BoundCall.Synthesized( syntax: exprSyntax, receiverOpt: collectionExpr, method: nullableValueGetter); } else { return new BoundBadExpression( exprSyntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create(collectionExpr), collectionExprType.GetNullableUnderlyingType()) { WasCompilerGenerated = true }; // Don't affect the type in the SemanticModel. } } return collectionExpr; } /// <summary> /// The spec describes an algorithm for finding the following types: /// 1) Collection type /// 2) Enumerator type /// 3) Element type /// /// The implementation details are a bit different. If we're iterating over a string or an array, then we don't need to record anything /// but the inferredType (in case the iteration variable is implicitly typed). If we're iterating over anything else, then we want the /// inferred type plus a ForEachEnumeratorInfo.Builder with: /// 1) Collection type /// 2) Element type /// 3) GetEnumerator (or GetAsyncEnumerator) method of the collection type (return type will be the enumerator type from the spec) /// 4) Current property and MoveNext (or MoveNextAsync) method of the enumerator type /// /// The caller will have to do some extra conversion checks before creating a ForEachEnumeratorInfo for the BoundForEachStatement. /// </summary> /// <param name="builder">Builder to fill in (partially, all but conversions).</param> /// <param name="collectionExpr">The expression over which to iterate.</param> /// <param name="diagnostics">Populated with binding diagnostics.</param> /// <returns>Partially populated (all but conversions) or null if there was an error.</returns> private bool GetEnumeratorInfo(ref ForEachEnumeratorInfo.Builder builder, ref BoundExpression collectionExpr, BindingDiagnosticBag diagnostics) { bool isAsync = IsAsync; builder.IsAsync = isAsync; EnumeratorResult found = GetEnumeratorInfo(ref builder, ref collectionExpr, isAsync, diagnostics); switch (found) { case EnumeratorResult.Succeeded: return true; case EnumeratorResult.FailedAndReported: return false; } TypeSymbol collectionExprType = collectionExpr.Type; if (string.IsNullOrEmpty(collectionExprType.Name) && collectionExpr.HasErrors) { return false; } if (collectionExprType.IsErrorType()) { return false; } // Retry with a different assumption about whether the foreach is async var ignoredBuilder = new ForEachEnumeratorInfo.Builder(); bool wrongAsync = GetEnumeratorInfo(ref ignoredBuilder, ref collectionExpr, !isAsync, BindingDiagnosticBag.Discarded) == EnumeratorResult.Succeeded; var errorCode = wrongAsync ? (isAsync ? ErrorCode.ERR_AwaitForEachMissingMemberWrongAsync : ErrorCode.ERR_ForEachMissingMemberWrongAsync) : (isAsync ? ErrorCode.ERR_AwaitForEachMissingMember : ErrorCode.ERR_ForEachMissingMember); diagnostics.Add(errorCode, _syntax.Expression.Location, collectionExprType, isAsync ? GetAsyncEnumeratorMethodName : GetEnumeratorMethodName); return false; } private enum EnumeratorResult { Succeeded, FailedNotReported, FailedAndReported } private EnumeratorResult GetEnumeratorInfo(ref ForEachEnumeratorInfo.Builder builder, ref BoundExpression collectionExpr, bool isAsync, BindingDiagnosticBag diagnostics) { TypeSymbol collectionExprType = collectionExpr.Type; if (collectionExprType is null) // There's no way to enumerate something without a type. { if (!ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) { // Anything else with a null type is a method group or anonymous function diagnostics.Add(ErrorCode.ERR_AnonMethGrpInForEach, _syntax.Expression.Location, collectionExpr.Display); } // CONSIDER: dev10 also reports ERR_ForEachMissingMember (i.e. failed pattern match). return EnumeratorResult.FailedAndReported; } if (collectionExpr.ResultKind == LookupResultKind.NotAValue) { // Short-circuiting to prevent strange behavior in the case where the collection // expression is a type expression and the type is enumerable. Debug.Assert(collectionExpr.HasAnyErrors); // should already have been reported return EnumeratorResult.FailedAndReported; } if (collectionExprType.Kind == SymbolKind.DynamicType && IsAsync) { diagnostics.Add(ErrorCode.ERR_BadDynamicAwaitForEach, _syntax.Expression.Location); return EnumeratorResult.FailedAndReported; } // The spec specifically lists the collection, enumerator, and element types for arrays and dynamic. if (collectionExprType.Kind == SymbolKind.ArrayType || collectionExprType.Kind == SymbolKind.DynamicType) { if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) { return EnumeratorResult.FailedAndReported; } builder = GetDefaultEnumeratorInfo(builder, diagnostics, collectionExprType); return EnumeratorResult.Succeeded; } var unwrappedCollectionExpr = UnwrapCollectionExpressionIfNullable(collectionExpr, diagnostics); var unwrappedCollectionExprType = unwrappedCollectionExpr.Type; if (SatisfiesGetEnumeratorPattern(ref builder, unwrappedCollectionExpr, isAsync, viaExtensionMethod: false, diagnostics)) { collectionExpr = unwrappedCollectionExpr; if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) { return EnumeratorResult.FailedAndReported; } return createPatternBasedEnumeratorResult(ref builder, unwrappedCollectionExpr, isAsync, viaExtensionMethod: false, diagnostics); } if (!isAsync && IsIEnumerable(unwrappedCollectionExprType)) { collectionExpr = unwrappedCollectionExpr; // This indicates a problem with the special IEnumerable type - it should have satisfied the GetEnumerator pattern. diagnostics.Add(ErrorCode.ERR_ForEachMissingMember, _syntax.Expression.Location, unwrappedCollectionExprType, GetEnumeratorMethodName); return EnumeratorResult.FailedAndReported; } if (isAsync && IsIAsyncEnumerable(unwrappedCollectionExprType)) { collectionExpr = unwrappedCollectionExpr; // This indicates a problem with the well-known IAsyncEnumerable type - it should have satisfied the GetAsyncEnumerator pattern. diagnostics.Add(ErrorCode.ERR_AwaitForEachMissingMember, _syntax.Expression.Location, unwrappedCollectionExprType, GetAsyncEnumeratorMethodName); return EnumeratorResult.FailedAndReported; } if (SatisfiesIEnumerableInterfaces(ref builder, unwrappedCollectionExpr, isAsync, diagnostics, unwrappedCollectionExprType) is not EnumeratorResult.FailedNotReported and var result) { collectionExpr = unwrappedCollectionExpr; return result; } // COMPAT: // In some rare cases, like MicroFramework, System.String does not implement foreach pattern. // For compat reasons we must still treat System.String as valid to use in a foreach // Similarly to the cases with array and dynamic, we will default to IEnumerable for binding purposes. // Lowering will not use iterator info with strings, so it is ok. if (!isAsync && collectionExprType.SpecialType == SpecialType.System_String) { if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) { return EnumeratorResult.FailedAndReported; } builder = GetDefaultEnumeratorInfo(builder, diagnostics, collectionExprType); return EnumeratorResult.Succeeded; } if (SatisfiesGetEnumeratorPattern(ref builder, collectionExpr, isAsync, viaExtensionMethod: true, diagnostics)) { return createPatternBasedEnumeratorResult(ref builder, collectionExpr, isAsync, viaExtensionMethod: true, diagnostics); } return EnumeratorResult.FailedNotReported; EnumeratorResult createPatternBasedEnumeratorResult(ref ForEachEnumeratorInfo.Builder builder, BoundExpression collectionExpr, bool isAsync, bool viaExtensionMethod, BindingDiagnosticBag diagnostics) { Debug.Assert((object)builder.GetEnumeratorInfo != null); Debug.Assert(!(viaExtensionMethod && builder.GetEnumeratorInfo.Method.Parameters.IsDefaultOrEmpty)); builder.CollectionType = viaExtensionMethod ? builder.GetEnumeratorInfo.Method.Parameters[0].Type : collectionExpr.Type; if (SatisfiesForEachPattern(ref builder, isAsync, diagnostics)) { builder.ElementTypeWithAnnotations = ((PropertySymbol)builder.CurrentPropertyGetter.AssociatedSymbol).TypeWithAnnotations; GetDisposalInfoForEnumerator(ref builder, collectionExpr, isAsync, diagnostics); return EnumeratorResult.Succeeded; } MethodSymbol getEnumeratorMethod = builder.GetEnumeratorInfo.Method; diagnostics.Add(isAsync ? ErrorCode.ERR_BadGetAsyncEnumerator : ErrorCode.ERR_BadGetEnumerator, _syntax.Expression.Location, getEnumeratorMethod.ReturnType, getEnumeratorMethod); return EnumeratorResult.FailedAndReported; } } private EnumeratorResult SatisfiesIEnumerableInterfaces(ref ForEachEnumeratorInfo.Builder builder, BoundExpression collectionExpr, bool isAsync, BindingDiagnosticBag diagnostics, TypeSymbol unwrappedCollectionExprType) { if (!AllInterfacesContainsIEnumerable(ref builder, unwrappedCollectionExprType, isAsync, diagnostics, out bool foundMultipleGenericIEnumerableInterfaces)) { return EnumeratorResult.FailedNotReported; } if (ReportConstantNullCollectionExpr(collectionExpr, diagnostics)) { return EnumeratorResult.FailedAndReported; } CSharpSyntaxNode errorLocationSyntax = _syntax.Expression; if (foundMultipleGenericIEnumerableInterfaces) { diagnostics.Add(isAsync ? ErrorCode.ERR_MultipleIAsyncEnumOfT : ErrorCode.ERR_MultipleIEnumOfT, errorLocationSyntax.Location, unwrappedCollectionExprType, isAsync ? this.Compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T) : this.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T)); return EnumeratorResult.FailedAndReported; } Debug.Assert((object)builder.CollectionType != null); NamedTypeSymbol collectionType = (NamedTypeSymbol)builder.CollectionType; if (collectionType.IsGenericType) { // If the type is generic, we have to search for the methods builder.ElementTypeWithAnnotations = collectionType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); MethodSymbol getEnumeratorMethod; if (isAsync) { Debug.Assert(IsIAsyncEnumerable(collectionType.OriginalDefinition)); getEnumeratorMethod = (MethodSymbol)GetWellKnownTypeMember(Compilation, WellKnownMember.System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator, diagnostics, errorLocationSyntax.Location, isOptional: false); // Well-known members are matched by signature: we shouldn't find it if it doesn't have exactly 1 parameter. Debug.Assert(getEnumeratorMethod is null or { ParameterCount: 1 }); if (getEnumeratorMethod?.Parameters[0].IsOptional == false) { // This indicates a problem with the well-known IAsyncEnumerable type - it should have an optional cancellation token. diagnostics.Add(ErrorCode.ERR_AwaitForEachMissingMember, _syntax.Expression.Location, unwrappedCollectionExprType, GetAsyncEnumeratorMethodName); return EnumeratorResult.FailedAndReported; } } else { Debug.Assert(collectionType.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T); getEnumeratorMethod = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Collections_Generic_IEnumerable_T__GetEnumerator, diagnostics, errorLocationSyntax); } MethodSymbol moveNextMethod = null; if ((object)getEnumeratorMethod != null) { MethodSymbol specificGetEnumeratorMethod = getEnumeratorMethod.AsMember(collectionType); TypeSymbol enumeratorType = specificGetEnumeratorMethod.ReturnType; // IAsyncEnumerable<T>.GetAsyncEnumerator has a default param, so let's fill it in builder.GetEnumeratorInfo = BindDefaultArguments( specificGetEnumeratorMethod, extensionReceiverOpt: null, expanded: false, collectionExpr.Syntax, diagnostics, // C# 8 shipped allowing the CancellationToken of `IAsyncEnumerable.GetAsyncEnumerator` to be non-optional, // filling in a default value in that case. https://github.com/dotnet/roslyn/issues/50182 tracks making // this an error and breaking the scenario. assertMissingParametersAreOptional: false); MethodSymbol currentPropertyGetter; if (isAsync) { Debug.Assert(enumeratorType.OriginalDefinition.Equals(Compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T))); MethodSymbol moveNextAsync = (MethodSymbol)GetWellKnownTypeMember(WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync, diagnostics, errorLocationSyntax.Location, isOptional: false); if ((object)moveNextAsync != null) { moveNextMethod = moveNextAsync.AsMember((NamedTypeSymbol)enumeratorType); } currentPropertyGetter = (MethodSymbol)GetWellKnownTypeMember(Compilation, WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__get_Current, diagnostics, errorLocationSyntax.Location, isOptional: false); } else { currentPropertyGetter = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Collections_Generic_IEnumerator_T__get_Current, diagnostics, errorLocationSyntax); } if ((object)currentPropertyGetter != null) { builder.CurrentPropertyGetter = currentPropertyGetter.AsMember((NamedTypeSymbol)enumeratorType); } } if (!isAsync) { // NOTE: MoveNext is actually inherited from System.Collections.IEnumerator moveNextMethod = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext, diagnostics, errorLocationSyntax); } // We're operating with well-known members: we know MoveNext/MoveNextAsync have no parameters if (moveNextMethod is not null) { builder.MoveNextInfo = MethodArgumentInfo.CreateParameterlessMethod(moveNextMethod); } } else { // Non-generic - use special members to avoid re-computing Debug.Assert(collectionType.SpecialType == SpecialType.System_Collections_IEnumerable); builder.GetEnumeratorInfo = GetParameterlessSpecialTypeMemberInfo(SpecialMember.System_Collections_IEnumerable__GetEnumerator, errorLocationSyntax, diagnostics); builder.CurrentPropertyGetter = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__get_Current, diagnostics, errorLocationSyntax); builder.MoveNextInfo = GetParameterlessSpecialTypeMemberInfo(SpecialMember.System_Collections_IEnumerator__MoveNext, errorLocationSyntax, diagnostics); builder.ElementTypeWithAnnotations = builder.CurrentPropertyGetter?.ReturnTypeWithAnnotations ?? TypeWithAnnotations.Create(GetSpecialType(SpecialType.System_Object, diagnostics, errorLocationSyntax)); Debug.Assert((object)builder.GetEnumeratorInfo == null || builder.GetEnumeratorInfo.Method.ReturnType.SpecialType == SpecialType.System_Collections_IEnumerator); } // We don't know the runtime type, so we will have to insert a runtime check for IDisposable (with a conditional call to IDisposable.Dispose). builder.NeedsDisposal = true; return EnumeratorResult.Succeeded; } private bool ReportConstantNullCollectionExpr(BoundExpression collectionExpr, BindingDiagnosticBag diagnostics) { if (collectionExpr.ConstantValue is { IsNull: true }) { // Spec seems to refer to null literals, but Dev10 reports anything known to be null. diagnostics.Add(ErrorCode.ERR_NullNotValid, _syntax.Expression.Location); return true; } return false; } private void GetDisposalInfoForEnumerator(ref ForEachEnumeratorInfo.Builder builder, BoundExpression expr, bool isAsync, BindingDiagnosticBag diagnostics) { // NOTE: if IDisposable is not available at all, no diagnostics will be reported - we will just assume that // the enumerator is not disposable. If it has IDisposable in its interface list, there will be a diagnostic there. // If IDisposable is available but its Dispose method is not, then diagnostics will be reported only if the enumerator // is potentially disposable. TypeSymbol enumeratorType = builder.GetEnumeratorInfo.Method.ReturnType; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // For async foreach, we don't do the runtime check if ((!enumeratorType.IsSealed && !isAsync) || this.Conversions.ClassifyImplicitConversionFromType(enumeratorType, isAsync ? this.Compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : this.Compilation.GetSpecialType(SpecialType.System_IDisposable), ref useSiteInfo).IsImplicit) { builder.NeedsDisposal = true; } else if (Compilation.IsFeatureEnabled(MessageID.IDS_FeatureUsingDeclarations) && (enumeratorType.IsRefLikeType || isAsync)) { // if it wasn't directly convertable to IDisposable, see if it is pattern-disposable // again, we throw away any binding diagnostics, and assume it's not disposable if we encounter errors var receiver = new BoundDisposableValuePlaceholder(_syntax, enumeratorType); MethodSymbol disposeMethod = TryFindDisposePatternMethod(receiver, _syntax, isAsync, BindingDiagnosticBag.Discarded); if (disposeMethod is object) { Debug.Assert(!disposeMethod.IsExtensionMethod); Debug.Assert(disposeMethod.ParameterRefKinds.IsDefaultOrEmpty); var argsBuilder = ArrayBuilder<BoundExpression>.GetInstance(disposeMethod.ParameterCount); var argsToParams = default(ImmutableArray<int>); bool expanded = disposeMethod.HasParamsParameter(); BindDefaultArguments( _syntax, disposeMethod.Parameters, argsBuilder, argumentRefKindsBuilder: null, ref argsToParams, out BitVector defaultArguments, expanded, enableCallerInfo: true, diagnostics); builder.NeedsDisposal = true; builder.PatternDisposeInfo = new MethodArgumentInfo(disposeMethod, argsBuilder.ToImmutableAndFree(), argsToParams, defaultArguments, expanded); } } diagnostics.Add(_syntax, useSiteInfo); } private ForEachEnumeratorInfo.Builder GetDefaultEnumeratorInfo(ForEachEnumeratorInfo.Builder builder, BindingDiagnosticBag diagnostics, TypeSymbol collectionExprType) { // NOTE: for arrays, we won't actually use any of these members - they're just for the API. builder.CollectionType = GetSpecialType(SpecialType.System_Collections_IEnumerable, diagnostics, _syntax); if (collectionExprType.IsDynamic()) { builder.ElementTypeWithAnnotations = TypeWithAnnotations.Create( ((_syntax as ForEachStatementSyntax)?.Type.IsVar == true) ? (TypeSymbol)DynamicTypeSymbol.Instance : GetSpecialType(SpecialType.System_Object, diagnostics, _syntax)); } else { builder.ElementTypeWithAnnotations = collectionExprType.SpecialType == SpecialType.System_String ? TypeWithAnnotations.Create(GetSpecialType(SpecialType.System_Char, diagnostics, _syntax)) : ((ArrayTypeSymbol)collectionExprType).ElementTypeWithAnnotations; } // CONSIDER: // For arrays and string none of these members will actually be emitted, so it seems strange to prevent compilation if they can't be found. // skip this work in the batch case? builder.GetEnumeratorInfo = GetParameterlessSpecialTypeMemberInfo(SpecialMember.System_Collections_IEnumerable__GetEnumerator, _syntax, diagnostics); builder.CurrentPropertyGetter = (MethodSymbol)GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__get_Current, diagnostics, _syntax); builder.MoveNextInfo = GetParameterlessSpecialTypeMemberInfo(SpecialMember.System_Collections_IEnumerator__MoveNext, _syntax, diagnostics); Debug.Assert((object)builder.GetEnumeratorInfo == null || TypeSymbol.Equals(builder.GetEnumeratorInfo.Method.ReturnType, this.Compilation.GetSpecialType(SpecialType.System_Collections_IEnumerator), TypeCompareKind.ConsiderEverything2)); // We don't know the runtime type, so we will have to insert a runtime check for IDisposable (with a conditional call to IDisposable.Dispose). builder.NeedsDisposal = true; return builder; } /// <summary> /// Check for a GetEnumerator (or GetAsyncEnumerator) method on collectionExprType. Failing to satisfy the pattern is not an error - /// it just means that we have to check for an interface instead. /// </summary> /// <param name="collectionExpr">Expression over which to iterate.</param> /// <param name="diagnostics">Populated with *warnings* if there are near misses.</param> /// <param name="builder">Builder to fill in. <see cref="ForEachEnumeratorInfo.Builder.GetEnumeratorInfo"/> set if the pattern in satisfied.</param> /// <returns>True if the method was found (still have to verify that the return (i.e. enumerator) type is acceptable).</returns> /// <remarks> /// Only adds warnings, so does not affect control flow (i.e. no need to check for failure). /// </remarks> private bool SatisfiesGetEnumeratorPattern(ref ForEachEnumeratorInfo.Builder builder, BoundExpression collectionExpr, bool isAsync, bool viaExtensionMethod, BindingDiagnosticBag diagnostics) { string methodName = isAsync ? GetAsyncEnumeratorMethodName : GetEnumeratorMethodName; MethodArgumentInfo getEnumeratorInfo; if (viaExtensionMethod) { getEnumeratorInfo = FindForEachPatternMethodViaExtension(collectionExpr, methodName, diagnostics); } else { var lookupResult = LookupResult.GetInstance(); getEnumeratorInfo = FindForEachPatternMethod(collectionExpr.Type, methodName, lookupResult, warningsOnly: true, diagnostics, isAsync); lookupResult.Free(); } builder.GetEnumeratorInfo = getEnumeratorInfo; return (object)getEnumeratorInfo != null; } /// <summary> /// Perform a lookup for the specified method on the specified type. Perform overload resolution /// on the lookup results. /// </summary> /// <param name="patternType">Type to search.</param> /// <param name="methodName">Method to search for.</param> /// <param name="lookupResult">Passed in for reusability.</param> /// <param name="warningsOnly">True if failures should result in warnings; false if they should result in errors.</param> /// <param name="diagnostics">Populated with binding diagnostics.</param> /// <returns>The desired method or null.</returns> private MethodArgumentInfo FindForEachPatternMethod(TypeSymbol patternType, string methodName, LookupResult lookupResult, bool warningsOnly, BindingDiagnosticBag diagnostics, bool isAsync) { Debug.Assert(lookupResult.IsClear); // Not using LookupOptions.MustBeInvocableMember because we don't want the corresponding lookup error. // We filter out non-methods below. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersInType( lookupResult, patternType, methodName, arity: 0, basesBeingResolved: null, options: LookupOptions.Default, originalBinder: this, diagnose: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(_syntax.Expression, useSiteInfo); if (!lookupResult.IsMultiViable) { ReportPatternMemberLookupDiagnostics(lookupResult, patternType, methodName, warningsOnly, diagnostics); return null; } ArrayBuilder<MethodSymbol> candidateMethods = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (Symbol member in lookupResult.Symbols) { if (member.Kind != SymbolKind.Method) { candidateMethods.Free(); if (warningsOnly) { ReportEnumerableWarning(diagnostics, patternType, member); } return null; } MethodSymbol method = (MethodSymbol)member; // SPEC VIOLATION: The spec says we should apply overload resolution, but Dev10 uses // some custom logic in ExpressionBinder.BindGrpToParams. The biggest difference // we've found (so far) is that it only considers methods with expected number of parameters // (i.e. doesn't work with "params" or optional parameters). // Note: for pattern-based lookup for `await foreach` we accept `GetAsyncEnumerator` and // `MoveNextAsync` methods with optional/params parameters. if (method.ParameterCount == 0 || isAsync) { candidateMethods.Add((MethodSymbol)member); } } MethodArgumentInfo patternInfo = PerformForEachPatternOverloadResolution(patternType, candidateMethods, warningsOnly, diagnostics, isAsync); candidateMethods.Free(); return patternInfo; } /// <summary> /// The overload resolution portion of FindForEachPatternMethod. /// If no arguments are passed in, then an empty argument list will be used. /// </summary> private MethodArgumentInfo PerformForEachPatternOverloadResolution(TypeSymbol patternType, ArrayBuilder<MethodSymbol> candidateMethods, bool warningsOnly, BindingDiagnosticBag diagnostics, bool isAsync) { var analyzedArguments = AnalyzedArguments.GetInstance(); var typeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // We create a dummy receiver of the invocation so MethodInvocationOverloadResolution knows it was invoked from an instance, not a type var dummyReceiver = new BoundImplicitReceiver(_syntax.Expression, patternType); this.OverloadResolution.MethodInvocationOverloadResolution( methods: candidateMethods, typeArguments: typeArguments, receiver: dummyReceiver, arguments: analyzedArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo); diagnostics.Add(_syntax.Expression, useSiteInfo); MethodSymbol result = null; MethodArgumentInfo info = null; if (overloadResolutionResult.Succeeded) { result = overloadResolutionResult.ValidResult.Member; if (result.IsStatic || result.DeclaredAccessibility != Accessibility.Public) { if (warningsOnly) { MessageID patternName = isAsync ? MessageID.IDS_FeatureAsyncStreams : MessageID.IDS_Collection; diagnostics.Add(ErrorCode.WRN_PatternNotPublicOrNotInstance, _syntax.Expression.Location, patternType, patternName.Localize(), result); } result = null; } else if (result.CallsAreOmitted(_syntax.SyntaxTree)) { // Calls to this method are omitted in the current syntax tree, i.e it is either a partial method with no implementation part OR a conditional method whose condition is not true in this source file. // We don't want to allow this case. result = null; } else { var argsToParams = overloadResolutionResult.ValidResult.Result.ArgsToParamsOpt; var expanded = overloadResolutionResult.ValidResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; BindDefaultArguments( _syntax, result.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out BitVector defaultArguments, expanded, enableCallerInfo: true, diagnostics); info = new MethodArgumentInfo(result, analyzedArguments.Arguments.ToImmutable(), argsToParams, defaultArguments, expanded); } } else if (overloadResolutionResult.GetAllApplicableMembers() is var applicableMembers && applicableMembers.Length > 1) { if (warningsOnly) { diagnostics.Add(ErrorCode.WRN_PatternIsAmbiguous, _syntax.Expression.Location, patternType, MessageID.IDS_Collection.Localize(), applicableMembers[0], applicableMembers[1]); } } overloadResolutionResult.Free(); analyzedArguments.Free(); typeArguments.Free(); return info; } private MethodArgumentInfo FindForEachPatternMethodViaExtension(BoundExpression collectionExpr, string methodName, BindingDiagnosticBag diagnostics) { var analyzedArguments = AnalyzedArguments.GetInstance(); var methodGroupResolutionResult = this.BindExtensionMethod( _syntax.Expression, methodName, analyzedArguments, collectionExpr, typeArgumentsWithAnnotations: default, isMethodGroupConversion: false, returnRefKind: default, returnType: null, withDependencies: diagnostics.AccumulatesDependencies); diagnostics.AddRange(methodGroupResolutionResult.Diagnostics); var overloadResolutionResult = methodGroupResolutionResult.OverloadResolutionResult; if (overloadResolutionResult?.Succeeded ?? false) { var result = overloadResolutionResult.ValidResult.Member; if (result.CallsAreOmitted(_syntax.SyntaxTree)) { // Calls to this method are omitted in the current syntax tree, i.e it is either a partial method with no implementation part OR a conditional method whose condition is not true in this source file. // We don't want to allow this case. methodGroupResolutionResult.Free(); analyzedArguments.Free(); return null; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var collectionConversion = this.Conversions.ClassifyConversionFromExpression(collectionExpr, result.Parameters[0].Type, ref useSiteInfo); diagnostics.Add(_syntax, useSiteInfo); // Unconditionally convert here, to match what we set the ConvertedExpression to in the main BoundForEachStatement node. Debug.Assert(!collectionConversion.IsUserDefined); collectionExpr = new BoundConversion( collectionExpr.Syntax, collectionExpr, collectionConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, result.Parameters[0].Type); var info = BindDefaultArguments( result, collectionExpr, expanded: overloadResolutionResult.ValidResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm, collectionExpr.Syntax, diagnostics); methodGroupResolutionResult.Free(); analyzedArguments.Free(); return info; } else if (overloadResolutionResult?.GetAllApplicableMembers() is { } applicableMembers && applicableMembers.Length > 1) { diagnostics.Add(ErrorCode.WRN_PatternIsAmbiguous, _syntax.Expression.Location, collectionExpr.Type, MessageID.IDS_Collection.Localize(), applicableMembers[0], applicableMembers[1]); } else if (overloadResolutionResult != null) { overloadResolutionResult.ReportDiagnostics( binder: this, location: _syntax.Expression.Location, nodeOpt: _syntax.Expression, diagnostics: diagnostics, name: methodName, receiver: null, invokedExpression: _syntax.Expression, arguments: methodGroupResolutionResult.AnalyzedArguments, memberGroup: methodGroupResolutionResult.MethodGroup.Methods.ToImmutable(), typeContainingConstructor: null, delegateTypeBeingInvoked: null); } methodGroupResolutionResult.Free(); analyzedArguments.Free(); return null; } /// <summary> /// Called after it is determined that the expression being enumerated is of a type that /// has a GetEnumerator (or GetAsyncEnumerator) method. Checks to see if the return type of the GetEnumerator /// method is suitable (i.e. has Current and MoveNext for regular case, /// or Current and MoveNextAsync for async case). /// </summary> /// <param name="builder">Must be non-null and contain a non-null GetEnumeratorMethod.</param> /// <param name="diagnostics">Will be populated with pattern diagnostics.</param> /// <returns>True if the return type has suitable members.</returns> /// <remarks> /// It seems that every failure path reports the same diagnostics, so that is left to the caller. /// </remarks> private bool SatisfiesForEachPattern(ref ForEachEnumeratorInfo.Builder builder, bool isAsync, BindingDiagnosticBag diagnostics) { Debug.Assert((object)builder.GetEnumeratorInfo.Method != null); MethodSymbol getEnumeratorMethod = builder.GetEnumeratorInfo.Method; TypeSymbol enumeratorType = getEnumeratorMethod.ReturnType; switch (enumeratorType.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.TypeParameter: // Not specifically mentioned in the spec, but consistent with Dev10. case TypeKind.Dynamic: // Not specifically mentioned in the spec, but consistent with Dev10. break; case TypeKind.Submission: // submission class is synthesized and should never appear in a foreach: throw ExceptionUtilities.UnexpectedValue(enumeratorType.TypeKind); default: return false; } // Use a try-finally since there are many return points LookupResult lookupResult = LookupResult.GetInstance(); try { // If we searched for the accessor directly, we could reuse FindForEachPatternMethod and we // wouldn't have to mangle CurrentPropertyName. However, Dev10 searches for the property and // then extracts the accessor, so we should do the same (in case of accessors with non-standard // names). CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersInType( lookupResult, enumeratorType, CurrentPropertyName, arity: 0, basesBeingResolved: null, options: LookupOptions.Default, // properties are not invocable - their accessors are originalBinder: this, diagnose: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(_syntax.Expression, useSiteInfo); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); if (!lookupResult.IsSingleViable) { ReportPatternMemberLookupDiagnostics(lookupResult, enumeratorType, CurrentPropertyName, warningsOnly: false, diagnostics: diagnostics); return false; } // lookupResult.IsSingleViable above guaranteed there is exactly one symbol. Symbol lookupSymbol = lookupResult.SingleSymbolOrDefault; Debug.Assert((object)lookupSymbol != null); if (lookupSymbol.IsStatic || lookupSymbol.DeclaredAccessibility != Accessibility.Public || lookupSymbol.Kind != SymbolKind.Property) { return false; } // NOTE: accessor can be inherited from overridden property MethodSymbol currentPropertyGetterCandidate = ((PropertySymbol)lookupSymbol).GetOwnOrInheritedGetMethod(); if ((object)currentPropertyGetterCandidate == null) { return false; } else { bool isAccessible = this.IsAccessible(currentPropertyGetterCandidate, ref useSiteInfo); diagnostics.Add(_syntax.Expression, useSiteInfo); if (!isAccessible) { // NOTE: per Dev10 and the spec, the property has to be public, but the accessor just has to be accessible return false; } } builder.CurrentPropertyGetter = currentPropertyGetterCandidate; lookupResult.Clear(); // Reuse the same LookupResult MethodArgumentInfo moveNextMethodCandidate = FindForEachPatternMethod(enumeratorType, isAsync ? MoveNextAsyncMethodName : MoveNextMethodName, lookupResult, warningsOnly: false, diagnostics, isAsync); if ((object)moveNextMethodCandidate == null || moveNextMethodCandidate.Method.IsStatic || moveNextMethodCandidate.Method.DeclaredAccessibility != Accessibility.Public || IsInvalidMoveNextMethod(moveNextMethodCandidate.Method, isAsync)) { return false; } builder.MoveNextInfo = moveNextMethodCandidate; return true; } finally { lookupResult.Free(); } } private bool IsInvalidMoveNextMethod(MethodSymbol moveNextMethodCandidate, bool isAsync) { if (isAsync) { // We'll verify the return type from `MoveNextAsync` when we try to bind the `await` for it return false; } // SPEC VIOLATION: Dev10 checks the return type of the original definition, rather than the return type of the actual method. return moveNextMethodCandidate.OriginalDefinition.ReturnType.SpecialType != SpecialType.System_Boolean; } private void ReportEnumerableWarning(BindingDiagnosticBag diagnostics, TypeSymbol enumeratorType, Symbol patternMemberCandidate) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (this.IsAccessible(patternMemberCandidate, ref useSiteInfo)) { diagnostics.Add(ErrorCode.WRN_PatternBadSignature, _syntax.Expression.Location, enumeratorType, MessageID.IDS_Collection.Localize(), patternMemberCandidate); } diagnostics.Add(_syntax.Expression, useSiteInfo); } private static bool IsIEnumerable(TypeSymbol type) { switch (((TypeSymbol)type.OriginalDefinition).SpecialType) { case SpecialType.System_Collections_IEnumerable: case SpecialType.System_Collections_Generic_IEnumerable_T: return true; default: return false; } } private bool IsIAsyncEnumerable(TypeSymbol type) { return type.OriginalDefinition.Equals(Compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T)); } /// <summary> /// Checks if the given type implements (or extends, in the case of an interface), /// System.Collections.IEnumerable or System.Collections.Generic.IEnumerable&lt;T&gt;, /// (or System.Collections.Generic.IAsyncEnumerable&lt;T&gt;) /// for at least one T. /// </summary> /// <param name="builder">builder to fill in CollectionType.</param> /// <param name="type">Type to check.</param> /// <param name="diagnostics" /> /// <param name="foundMultiple">True if multiple T's are found.</param> /// <returns>True if some IEnumerable is found (may still be ambiguous).</returns> private bool AllInterfacesContainsIEnumerable( ref ForEachEnumeratorInfo.Builder builder, TypeSymbol type, bool isAsync, BindingDiagnosticBag diagnostics, out bool foundMultiple) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); NamedTypeSymbol implementedIEnumerable = GetIEnumerableOfT(type, isAsync, Compilation, ref useSiteInfo, out foundMultiple); // Prefer generic to non-generic, unless it is inaccessible. if (((object)implementedIEnumerable == null) || !this.IsAccessible(implementedIEnumerable, ref useSiteInfo)) { implementedIEnumerable = null; if (!isAsync) { var implementedNonGeneric = this.Compilation.GetSpecialType(SpecialType.System_Collections_IEnumerable); if ((object)implementedNonGeneric != null) { var conversion = this.Conversions.ClassifyImplicitConversionFromType(type, implementedNonGeneric, ref useSiteInfo); if (conversion.IsImplicit) { implementedIEnumerable = implementedNonGeneric; } } } } diagnostics.Add(_syntax.Expression, useSiteInfo); builder.CollectionType = implementedIEnumerable; return (object)implementedIEnumerable != null; } internal static NamedTypeSymbol GetIEnumerableOfT(TypeSymbol type, bool isAsync, CSharpCompilation compilation, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, out bool foundMultiple) { NamedTypeSymbol implementedIEnumerable = null; foundMultiple = false; if (type.TypeKind == TypeKind.TypeParameter) { var typeParameter = (TypeParameterSymbol)type; var allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo) .Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); GetIEnumerableOfT(allInterfaces, isAsync, compilation, ref @implementedIEnumerable, ref foundMultiple); } else { GetIEnumerableOfT(type.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo), isAsync, compilation, ref @implementedIEnumerable, ref foundMultiple); } return implementedIEnumerable; } private static void GetIEnumerableOfT(ImmutableArray<NamedTypeSymbol> interfaces, bool isAsync, CSharpCompilation compilation, ref NamedTypeSymbol result, ref bool foundMultiple) { if (foundMultiple) { return; } interfaces = MethodTypeInferrer.ModuloReferenceTypeNullabilityDifferences(interfaces, VarianceKind.In); foreach (NamedTypeSymbol @interface in interfaces) { if (IsIEnumerableT(@interface.OriginalDefinition, isAsync, compilation)) { if ((object)result == null || TypeSymbol.Equals(@interface, result, TypeCompareKind.IgnoreTupleNames)) { result = @interface; } else { foundMultiple = true; return; } } } } internal static bool IsIEnumerableT(TypeSymbol type, bool isAsync, CSharpCompilation compilation) { if (isAsync) { return type.Equals(compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T)); } else { return type.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T; } } /// <summary> /// Report appropriate diagnostics when lookup of a pattern member (i.e. GetEnumerator, Current, or MoveNext) fails. /// </summary> /// <param name="lookupResult">Failed lookup result.</param> /// <param name="patternType">Type in which member was looked up.</param> /// <param name="memberName">Name of looked up member.</param> /// <param name="warningsOnly">True if failures should result in warnings; false if they should result in errors.</param> /// <param name="diagnostics">Populated appropriately.</param> private void ReportPatternMemberLookupDiagnostics(LookupResult lookupResult, TypeSymbol patternType, string memberName, bool warningsOnly, BindingDiagnosticBag diagnostics) { if (lookupResult.Symbols.Any()) { if (warningsOnly) { ReportEnumerableWarning(diagnostics, patternType, lookupResult.Symbols.First()); } else { lookupResult.Clear(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersInType( lookupResult, patternType, memberName, arity: 0, basesBeingResolved: null, options: LookupOptions.Default, originalBinder: this, diagnose: true, useSiteInfo: ref useSiteInfo); diagnostics.Add(_syntax.Expression, useSiteInfo); if (lookupResult.Error != null) { diagnostics.Add(lookupResult.Error, _syntax.Expression.Location); } } } else if (!warningsOnly) { diagnostics.Add(ErrorCode.ERR_NoSuchMember, _syntax.Expression.Location, patternType, memberName); } } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (_syntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _syntax; } } private MethodArgumentInfo GetParameterlessSpecialTypeMemberInfo(SpecialMember member, SyntaxNode syntax, BindingDiagnosticBag diagnostics) { var resolvedMember = (MethodSymbol)GetSpecialTypeMember(member, diagnostics, syntax); Debug.Assert(resolvedMember is null or { ParameterCount: 0 }); return resolvedMember is not null ? MethodArgumentInfo.CreateParameterlessMethod(resolvedMember) : null; } /// <param name="extensionReceiverOpt">If method is an extension method, this must be non-null.</param> private MethodArgumentInfo BindDefaultArguments(MethodSymbol method, BoundExpression extensionReceiverOpt, bool expanded, SyntaxNode syntax, BindingDiagnosticBag diagnostics, bool assertMissingParametersAreOptional = true) { Debug.Assert((extensionReceiverOpt != null) == method.IsExtensionMethod); if (method.ParameterCount == 0) { return MethodArgumentInfo.CreateParameterlessMethod(method); } var argsBuilder = ArrayBuilder<BoundExpression>.GetInstance(method.ParameterCount); if (method.IsExtensionMethod) { argsBuilder.Add(extensionReceiverOpt); } ImmutableArray<int> argsToParams = default; BindDefaultArguments( syntax, method.Parameters, argsBuilder, argumentRefKindsBuilder: null, ref argsToParams, defaultArguments: out BitVector defaultArguments, expanded, enableCallerInfo: true, diagnostics, assertMissingParametersAreOptional); return new MethodArgumentInfo(method, argsBuilder.ToImmutableAndFree(), argsToParams, defaultArguments, expanded); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/CSharpTest2/Recommendations/CatchKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class CatchKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTry() { await VerifyKeywordAsync(AddInsideMethod( @"try { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTryCatch() { await VerifyKeywordAsync(AddInsideMethod( @"try { } catch { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFinally() { await VerifyAbsenceAsync(AddInsideMethod( @"try { } finally { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterBlock() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) { Console.WriteLine(); } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterCatch() { await VerifyAbsenceAsync(AddInsideMethod( @"try { } catch $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync(@"class C { $$ }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class CatchKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTry() { await VerifyKeywordAsync(AddInsideMethod( @"try { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTryCatch() { await VerifyKeywordAsync(AddInsideMethod( @"try { } catch { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFinally() { await VerifyAbsenceAsync(AddInsideMethod( @"try { } finally { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterBlock() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) { Console.WriteLine(); } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterCatch() { await VerifyAbsenceAsync(AddInsideMethod( @"try { } catch $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync(@"class C { $$ }"); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Analyzers/CSharp/Tests/AddRequiredParentheses/AddRequiredPatternParenthesesTests.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.AddRequiredParentheses; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.AddRequiredParentheses; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddRequiredParentheses { public partial class AddRequiredPatternParenthesesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public AddRequiredPatternParenthesesTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer(), new AddRequiredParenthesesCodeFixProvider()); private Task TestMissingAsync(string initialMarkup, OptionsCollection options) => TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options)); private Task TestAsync(string initialMarkup, string expected, OptionsCollection options) => TestInRegularAndScript1Async(initialMarkup, expected, parameters: new TestParameters(options: options)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestLogicalPrecedence() { await TestAsync( @"class C { void M(object o) { object x = o is a or b $$and c; } }", @"class C { void M(object o) { object x = o is a or (b and c); } }", RequireAllParenthesesForClarity); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestNoLogicalOnLowerPrecedence() { await TestMissingAsync( @"class C { void M(object o) { object x = o is a $$or b and c; } }", RequireAllParenthesesForClarity); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestNotIfLogicalPrecedenceStaysTheSame() { await TestMissingAsync( @"class C { void M(object o) { object x = o is a or b $$or c; } }", RequireAllParenthesesForClarity); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestNotIfLogicalPrecedenceIsNotEnforced() { await TestMissingAsync( @"class C { void M(object o) { object x = o is a or b $$or c; } }", RequireArithmeticBinaryParenthesesForClarity); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestLogicalPrecedenceMultipleEqualPrecedenceParts1() { await TestAsync( @"class C { void M(object o) { object x = o is a or b $$and c and d; } }", @"class C { void M(object o) { object x = o is a or (b and c and d); } }", RequireAllParenthesesForClarity); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestLogicalPrecedenceMultipleEqualPrecedenceParts2() { await TestAsync( @"class C { void M(object o) { object x = o is a or b and c $$and d; } }", @"class C { void M(object o) { object x = o is a or (b and c and d); } }", RequireAllParenthesesForClarity); } } }
// Licensed to the .NET Foundation under one or more 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.AddRequiredParentheses; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.AddRequiredParentheses; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddRequiredParentheses { public partial class AddRequiredPatternParenthesesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public AddRequiredPatternParenthesesTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer(), new AddRequiredParenthesesCodeFixProvider()); private Task TestMissingAsync(string initialMarkup, OptionsCollection options) => TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: options)); private Task TestAsync(string initialMarkup, string expected, OptionsCollection options) => TestInRegularAndScript1Async(initialMarkup, expected, parameters: new TestParameters(options: options)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestLogicalPrecedence() { await TestAsync( @"class C { void M(object o) { object x = o is a or b $$and c; } }", @"class C { void M(object o) { object x = o is a or (b and c); } }", RequireAllParenthesesForClarity); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestNoLogicalOnLowerPrecedence() { await TestMissingAsync( @"class C { void M(object o) { object x = o is a $$or b and c; } }", RequireAllParenthesesForClarity); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestNotIfLogicalPrecedenceStaysTheSame() { await TestMissingAsync( @"class C { void M(object o) { object x = o is a or b $$or c; } }", RequireAllParenthesesForClarity); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestNotIfLogicalPrecedenceIsNotEnforced() { await TestMissingAsync( @"class C { void M(object o) { object x = o is a or b $$or c; } }", RequireArithmeticBinaryParenthesesForClarity); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestLogicalPrecedenceMultipleEqualPrecedenceParts1() { await TestAsync( @"class C { void M(object o) { object x = o is a or b $$and c and d; } }", @"class C { void M(object o) { object x = o is a or (b and c and d); } }", RequireAllParenthesesForClarity); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddRequiredParentheses)] public async Task TestLogicalPrecedenceMultipleEqualPrecedenceParts2() { await TestAsync( @"class C { void M(object o) { object x = o is a or b and c $$and d; } }", @"class C { void M(object o) { object x = o is a or (b and c and d); } }", RequireAllParenthesesForClarity); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/LocalSlotMappingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader.Tools; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class LocalSlotMappingTests : EditAndContinueTestBase { /// <summary> /// If no changes were made we don't produce a syntax map. /// If we don't have syntax map and preserve variables is true we should still successfully map the locals to their previous slots. /// </summary> [Fact] public void SlotMappingWithNoChanges() { var source0 = @" using System; class C { static void Main(string[] args) { var b = true; do { Console.WriteLine(""hi""); } while (b == true); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source0); var v0 = CompileAndVerify(compilation0); var methodData0 = v0.TestData.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); v0.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0, //b bool V_1) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 -IL_0003: nop -IL_0004: ldstr ""hi"" IL_0009: call ""void System.Console.WriteLine(string)"" IL_000e: nop -IL_000f: nop -IL_0010: ldloc.0 IL_0011: stloc.1 ~IL_0012: ldloc.1 IL_0013: brtrue.s IL_0003 -IL_0015: ret }", sequencePoints: "C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, syntaxMap: null, preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0, //b bool V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: nop IL_0004: ldstr ""hi"" IL_0009: call ""void System.Console.WriteLine(string)"" IL_000e: nop IL_000f: nop IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldloc.1 IL_0013: brtrue.s IL_0003 IL_0015: ret }"); } [Fact] public void OutOfOrderUserLocals() { var source = WithWindowsLineBreaks(@" using System; public class C { public static void M() { for (int i = 1; i < 1; i++) Console.WriteLine(1); for (int i = 1; i < 2; i++) Console.WriteLine(2); int j; for (j = 1; j < 3; j++) Console.WriteLine(3); } }"); var compilation0 = CreateCompilation(source, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 75 (0x4b) .maxstack 2 .locals init (int V_0, //j int V_1, //i bool V_2, int V_3, //i bool V_4, bool V_5) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: br.s IL_0010 IL_0005: ldc.i4.1 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: ldloc.1 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.1 IL_0012: clt IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: brtrue.s IL_0005 IL_0018: ldc.i4.1 IL_0019: stloc.3 IL_001a: br.s IL_0027 IL_001c: ldc.i4.2 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: ldloc.3 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.3 IL_0027: ldloc.3 IL_0028: ldc.i4.2 IL_0029: clt IL_002b: stloc.s V_4 IL_002d: ldloc.s V_4 IL_002f: brtrue.s IL_001c IL_0031: ldc.i4.1 IL_0032: stloc.0 IL_0033: br.s IL_0040 IL_0035: ldc.i4.3 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldc.i4.1 IL_003e: add IL_003f: stloc.0 IL_0040: ldloc.0 IL_0041: ldc.i4.3 IL_0042: clt IL_0044: stloc.s V_5 IL_0046: ldloc.s V_5 IL_0048: brtrue.s IL_0035 IL_004a: ret } "); v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""135"" /> <slot kind=""0"" offset=""20"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""0"" offset=""79"" /> <slot kind=""1"" offset=""70"" /> <slot kind=""1"" offset=""147"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""14"" endLine=""8"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""8"" startColumn=""37"" endLine=""8"" endColumn=""58"" document=""1"" /> <entry offset=""0xc"" startLine=""8"" startColumn=""32"" endLine=""8"" endColumn=""35"" document=""1"" /> <entry offset=""0x10"" startLine=""8"" startColumn=""25"" endLine=""8"" endColumn=""30"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x18"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""9"" startColumn=""37"" endLine=""9"" endColumn=""58"" document=""1"" /> <entry offset=""0x23"" startLine=""9"" startColumn=""32"" endLine=""9"" endColumn=""35"" document=""1"" /> <entry offset=""0x27"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x2d"" hidden=""true"" document=""1"" /> <entry offset=""0x31"" startLine=""12"" startColumn=""14"" endLine=""12"" endColumn=""19"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" startLine=""12"" startColumn=""33"" endLine=""12"" endColumn=""54"" document=""1"" /> <entry offset=""0x3c"" startLine=""12"" startColumn=""28"" endLine=""12"" endColumn=""31"" document=""1"" /> <entry offset=""0x40"" startLine=""12"" startColumn=""21"" endLine=""12"" endColumn=""26"" document=""1"" /> <entry offset=""0x46"" hidden=""true"" document=""1"" /> <entry offset=""0x4a"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4b""> <namespace name=""System"" /> <local name=""j"" il_index=""0"" il_start=""0x0"" il_end=""0x4b"" attributes=""0"" /> <scope startOffset=""0x1"" endOffset=""0x18""> <local name=""i"" il_index=""1"" il_start=""0x1"" il_end=""0x18"" attributes=""0"" /> </scope> <scope startOffset=""0x18"" endOffset=""0x31""> <local name=""i"" il_index=""3"" il_start=""0x18"" il_end=""0x31"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); var symReader = v0.CreateSymReader(); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), symReader.GetEncMethodDebugInfo); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // check that all user-defined and long-lived synthesized local slots are reused diff1.VerifyIL("C.M", @" { // Code size 75 (0x4b) .maxstack 2 .locals init (int V_0, //j int V_1, //i bool V_2, int V_3, //i bool V_4, bool V_5) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: br.s IL_0010 IL_0005: ldc.i4.1 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: ldloc.1 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.1 IL_0012: clt IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: brtrue.s IL_0005 IL_0018: ldc.i4.1 IL_0019: stloc.3 IL_001a: br.s IL_0027 IL_001c: ldc.i4.2 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: ldloc.3 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.3 IL_0027: ldloc.3 IL_0028: ldc.i4.2 IL_0029: clt IL_002b: stloc.s V_4 IL_002d: ldloc.s V_4 IL_002f: brtrue.s IL_001c IL_0031: ldc.i4.1 IL_0032: stloc.0 IL_0033: br.s IL_0040 IL_0035: ldc.i4.3 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldc.i4.1 IL_003e: add IL_003f: stloc.0 IL_0040: ldloc.0 IL_0041: ldc.i4.3 IL_0042: clt IL_0044: stloc.s V_5 IL_0046: ldloc.s V_5 IL_0048: brtrue.s IL_0035 IL_004a: ret } "); } /// <summary> /// Enc debug info is only present in debug builds. /// </summary> [Fact] public void DebugOnly() { var source = WithWindowsLineBreaks( @"class C { static System.IDisposable F() { return null; } static void M() { lock (F()) { } using (F()) { } } }"); var debug = CreateCompilation(source, options: TestOptions.DebugDll); var release = CreateCompilation(source, options: TestOptions.ReleaseDll); CompileAndVerify(debug).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""3"" offset=""11"" /> <slot kind=""2"" offset=""11"" /> <slot kind=""4"" offset=""35"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""19"" document=""1"" /> <entry offset=""0x12"" startLine=""9"" startColumn=""20"" endLine=""9"" endColumn=""21"" document=""1"" /> <entry offset=""0x13"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x20"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x27"" startLine=""10"" startColumn=""21"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0x28"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); CompileAndVerify(release).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""19"" document=""1"" /> <entry offset=""0x10"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x22"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x24"" hidden=""true"" document=""1"" /> <entry offset=""0x2d"" hidden=""true"" document=""1"" /> <entry offset=""0x2e"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void Using() { var source = WithWindowsLineBreaks( @"class C : System.IDisposable { public void Dispose() { } static System.IDisposable F() { return new C(); } static void M() { using (F()) { using (var u = F()) { } using (F()) { } } } }"); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), m => methodData0.GetEncDebugInfo()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 65 (0x41) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1, //u System.IDisposable V_2) IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: call ""System.IDisposable C.F()"" IL_000d: stloc.1 .try { IL_000e: nop IL_000f: nop IL_0010: leave.s IL_001d } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001c IL_0015: ldloc.1 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } IL_001d: call ""System.IDisposable C.F()"" IL_0022: stloc.2 .try { IL_0023: nop IL_0024: nop IL_0025: leave.s IL_0032 } finally { IL_0027: ldloc.2 IL_0028: brfalse.s IL_0031 IL_002a: ldloc.2 IL_002b: callvirt ""void System.IDisposable.Dispose()"" IL_0030: nop IL_0031: endfinally } IL_0032: nop IL_0033: leave.s IL_0040 } finally { IL_0035: ldloc.0 IL_0036: brfalse.s IL_003f IL_0038: ldloc.0 IL_0039: callvirt ""void System.IDisposable.Dispose()"" IL_003e: nop IL_003f: endfinally } IL_0040: ret }"); } [Fact] public void Lock() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { lock (F()) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 66 (0x42) .maxstack 2 .locals init (object V_0, bool V_1, object V_2, bool V_3) -IL_0000: nop -IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop -IL_0012: nop -IL_0013: call ""object C.F()"" IL_0018: stloc.2 IL_0019: ldc.i4.0 IL_001a: stloc.3 .try { IL_001b: ldloc.2 IL_001c: ldloca.s V_3 IL_001e: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0023: nop -IL_0024: nop -IL_0025: nop IL_0026: leave.s IL_0033 } finally { ~IL_0028: ldloc.3 IL_0029: brfalse.s IL_0032 IL_002b: ldloc.2 IL_002c: call ""void System.Threading.Monitor.Exit(object)"" IL_0031: nop ~IL_0032: endfinally } -IL_0033: nop IL_0034: leave.s IL_0041 } finally { ~IL_0036: ldloc.1 IL_0037: brfalse.s IL_0040 IL_0039: ldloc.0 IL_003a: call ""void System.Threading.Monitor.Exit(object)"" IL_003f: nop ~IL_0040: endfinally } -IL_0041: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Using Monitor.Enter(object). /// </summary> [Fact] public void Lock_Pre40() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { } } }"; var compilation0 = CreateEmptyCompilation(source, options: TestOptions.DebugDll, references: new[] { MscorlibRef_v20 }); var compilation1 = CreateEmptyCompilation(source, options: TestOptions.DebugDll, references: new[] { MscorlibRef_v20 }); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 27 (0x1b) .maxstack 1 .locals init (object V_0) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void System.Threading.Monitor.Enter(object)"" IL_000d: nop .try { IL_000e: nop IL_000f: nop IL_0010: leave.s IL_001a } finally { IL_0012: ldloc.0 IL_0013: call ""void System.Threading.Monitor.Exit(object)"" IL_0018: nop IL_0019: endfinally } IL_001a: ret }"); } [Fact] public void Fixed() { var source = @"class C { unsafe static void M(string s, int[] i) { fixed (char *p = s) { fixed (int *q = i) { } fixed (char *r = s) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 81 (0x51) .maxstack 2 .locals init (char* V_0, //p pinned string V_1, int* V_2, //q [unchanged] V_3, char* V_4, //r pinned string V_5, pinned int[] V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.1 IL_0003: ldloc.1 IL_0004: conv.u IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0011 IL_0009: ldloc.0 IL_000a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_000f: add IL_0010: stloc.0 IL_0011: nop IL_0012: ldarg.1 IL_0013: dup IL_0014: stloc.s V_6 IL_0016: brfalse.s IL_001e IL_0018: ldloc.s V_6 IL_001a: ldlen IL_001b: conv.i4 IL_001c: brtrue.s IL_0023 IL_001e: ldc.i4.0 IL_001f: conv.u IL_0020: stloc.2 IL_0021: br.s IL_002d IL_0023: ldloc.s V_6 IL_0025: ldc.i4.0 IL_0026: ldelema ""int"" IL_002b: conv.u IL_002c: stloc.2 IL_002d: nop IL_002e: nop IL_002f: ldnull IL_0030: stloc.s V_6 IL_0032: ldarg.0 IL_0033: stloc.s V_5 IL_0035: ldloc.s V_5 IL_0037: conv.u IL_0038: stloc.s V_4 IL_003a: ldloc.s V_4 IL_003c: brfalse.s IL_0048 IL_003e: ldloc.s V_4 IL_0040: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_0045: add IL_0046: stloc.s V_4 IL_0048: nop IL_0049: nop IL_004a: ldnull IL_004b: stloc.s V_5 IL_004d: nop IL_004e: ldnull IL_004f: stloc.1 IL_0050: ret }"); } [WorkItem(770053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770053")] [Fact] public void FixedMultiple() { var source = @"class C { unsafe static void M(string s1, string s2, string s3, string s4) { fixed (char* p1 = s1, p2 = s2) { *p1 = *p2; } fixed (char* p1 = s1, p3 = s3, p2 = s4) { *p1 = *p2; *p2 = *p3; fixed (char *p4 = s2) { *p3 = *p4; } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 166 (0xa6) .maxstack 2 .locals init (char* V_0, //p1 char* V_1, //p2 pinned string V_2, pinned string V_3, char* V_4, //p1 char* V_5, //p3 char* V_6, //p2 pinned string V_7, pinned string V_8, pinned string V_9, char* V_10, //p4 pinned string V_11) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: conv.u IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0011 IL_0009: ldloc.0 IL_000a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_000f: add IL_0010: stloc.0 IL_0011: ldarg.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: conv.u IL_0015: stloc.1 IL_0016: ldloc.1 IL_0017: brfalse.s IL_0021 IL_0019: ldloc.1 IL_001a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_001f: add IL_0020: stloc.1 IL_0021: nop IL_0022: ldloc.0 IL_0023: ldloc.1 IL_0024: ldind.u2 IL_0025: stind.i2 IL_0026: nop IL_0027: ldnull IL_0028: stloc.2 IL_0029: ldnull IL_002a: stloc.3 IL_002b: ldarg.0 IL_002c: stloc.s V_7 IL_002e: ldloc.s V_7 IL_0030: conv.u IL_0031: stloc.s V_4 IL_0033: ldloc.s V_4 IL_0035: brfalse.s IL_0041 IL_0037: ldloc.s V_4 IL_0039: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_003e: add IL_003f: stloc.s V_4 IL_0041: ldarg.2 IL_0042: stloc.s V_8 IL_0044: ldloc.s V_8 IL_0046: conv.u IL_0047: stloc.s V_5 IL_0049: ldloc.s V_5 IL_004b: brfalse.s IL_0057 IL_004d: ldloc.s V_5 IL_004f: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_0054: add IL_0055: stloc.s V_5 IL_0057: ldarg.3 IL_0058: stloc.s V_9 IL_005a: ldloc.s V_9 IL_005c: conv.u IL_005d: stloc.s V_6 IL_005f: ldloc.s V_6 IL_0061: brfalse.s IL_006d IL_0063: ldloc.s V_6 IL_0065: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_006a: add IL_006b: stloc.s V_6 IL_006d: nop IL_006e: ldloc.s V_4 IL_0070: ldloc.s V_6 IL_0072: ldind.u2 IL_0073: stind.i2 IL_0074: ldloc.s V_6 IL_0076: ldloc.s V_5 IL_0078: ldind.u2 IL_0079: stind.i2 IL_007a: ldarg.1 IL_007b: stloc.s V_11 IL_007d: ldloc.s V_11 IL_007f: conv.u IL_0080: stloc.s V_10 IL_0082: ldloc.s V_10 IL_0084: brfalse.s IL_0090 IL_0086: ldloc.s V_10 IL_0088: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_008d: add IL_008e: stloc.s V_10 IL_0090: nop IL_0091: ldloc.s V_5 IL_0093: ldloc.s V_10 IL_0095: ldind.u2 IL_0096: stind.i2 IL_0097: nop IL_0098: ldnull IL_0099: stloc.s V_11 IL_009b: nop IL_009c: ldnull IL_009d: stloc.s V_7 IL_009f: ldnull IL_00a0: stloc.s V_8 IL_00a2: ldnull IL_00a3: stloc.s V_9 IL_00a5: ret } "); } [Fact] public void ForEach() { var source = @"using System.Collections; using System.Collections.Generic; class C { static IEnumerable F1() { return null; } static List<object> F2() { return null; } static IEnumerable F3() { return null; } static List<object> F4() { return null; } static void M() { foreach (var @x in F1()) { foreach (object y in F2()) { } } foreach (var x in F4()) { foreach (var y in F3()) { } foreach (var z in F2()) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 272 (0x110) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, object V_1, //x System.Collections.Generic.List<object>.Enumerator V_2, object V_3, //y [unchanged] V_4, System.Collections.Generic.List<object>.Enumerator V_5, object V_6, //x System.Collections.IEnumerator V_7, object V_8, //y System.Collections.Generic.List<object>.Enumerator V_9, object V_10, //z System.IDisposable V_11) IL_0000: nop IL_0001: nop IL_0002: call ""System.Collections.IEnumerable C.F1()"" IL_0007: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_000c: stloc.0 .try { IL_000d: br.s IL_004a IL_000f: ldloc.0 IL_0010: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0015: stloc.1 IL_0016: nop IL_0017: nop IL_0018: call ""System.Collections.Generic.List<object> C.F2()"" IL_001d: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_0022: stloc.2 .try { IL_0023: br.s IL_002f IL_0025: ldloca.s V_2 IL_0027: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_002c: stloc.3 IL_002d: nop IL_002e: nop IL_002f: ldloca.s V_2 IL_0031: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_0036: brtrue.s IL_0025 IL_0038: leave.s IL_0049 } finally { IL_003a: ldloca.s V_2 IL_003c: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_0042: callvirt ""void System.IDisposable.Dispose()"" IL_0047: nop IL_0048: endfinally } IL_0049: nop IL_004a: ldloc.0 IL_004b: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0050: brtrue.s IL_000f IL_0052: leave.s IL_0069 } finally { IL_0054: ldloc.0 IL_0055: isinst ""System.IDisposable"" IL_005a: stloc.s V_11 IL_005c: ldloc.s V_11 IL_005e: brfalse.s IL_0068 IL_0060: ldloc.s V_11 IL_0062: callvirt ""void System.IDisposable.Dispose()"" IL_0067: nop IL_0068: endfinally } IL_0069: nop IL_006a: call ""System.Collections.Generic.List<object> C.F4()"" IL_006f: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_0074: stloc.s V_5 .try { IL_0076: br.s IL_00f2 IL_0078: ldloca.s V_5 IL_007a: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_007f: stloc.s V_6 IL_0081: nop IL_0082: nop IL_0083: call ""System.Collections.IEnumerable C.F3()"" IL_0088: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_008d: stloc.s V_7 .try { IL_008f: br.s IL_009c IL_0091: ldloc.s V_7 IL_0093: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0098: stloc.s V_8 IL_009a: nop IL_009b: nop IL_009c: ldloc.s V_7 IL_009e: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_00a3: brtrue.s IL_0091 IL_00a5: leave.s IL_00bd } finally { IL_00a7: ldloc.s V_7 IL_00a9: isinst ""System.IDisposable"" IL_00ae: stloc.s V_11 IL_00b0: ldloc.s V_11 IL_00b2: brfalse.s IL_00bc IL_00b4: ldloc.s V_11 IL_00b6: callvirt ""void System.IDisposable.Dispose()"" IL_00bb: nop IL_00bc: endfinally } IL_00bd: nop IL_00be: call ""System.Collections.Generic.List<object> C.F2()"" IL_00c3: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_00c8: stloc.s V_9 .try { IL_00ca: br.s IL_00d7 IL_00cc: ldloca.s V_9 IL_00ce: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_00d3: stloc.s V_10 IL_00d5: nop IL_00d6: nop IL_00d7: ldloca.s V_9 IL_00d9: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_00de: brtrue.s IL_00cc IL_00e0: leave.s IL_00f1 } finally { IL_00e2: ldloca.s V_9 IL_00e4: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_00ea: callvirt ""void System.IDisposable.Dispose()"" IL_00ef: nop IL_00f0: endfinally } IL_00f1: nop IL_00f2: ldloca.s V_5 IL_00f4: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_00f9: brtrue IL_0078 IL_00fe: leave.s IL_010f } finally { IL_0100: ldloca.s V_5 IL_0102: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_0108: callvirt ""void System.IDisposable.Dispose()"" IL_010d: nop IL_010e: endfinally } IL_010f: ret }"); } [Fact] public void ForEachArray1() { var source = @"class C { static void M(double[,,] c) { foreach (var x in c) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 111 (0x6f) .maxstack 4 .locals init (double[,,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, int V_6, double V_7) //x -IL_0000: nop -IL_0001: nop -IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldc.i4.0 IL_0006: callvirt ""int System.Array.GetUpperBound(int)"" IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: callvirt ""int System.Array.GetUpperBound(int)"" IL_0013: stloc.2 IL_0014: ldloc.0 IL_0015: ldc.i4.2 IL_0016: callvirt ""int System.Array.GetUpperBound(int)"" IL_001b: stloc.3 IL_001c: ldloc.0 IL_001d: ldc.i4.0 IL_001e: callvirt ""int System.Array.GetLowerBound(int)"" IL_0023: stloc.s V_4 ~IL_0025: br.s IL_0069 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: callvirt ""int System.Array.GetLowerBound(int)"" IL_002e: stloc.s V_5 ~IL_0030: br.s IL_005e IL_0032: ldloc.0 IL_0033: ldc.i4.2 IL_0034: callvirt ""int System.Array.GetLowerBound(int)"" IL_0039: stloc.s V_6 ~IL_003b: br.s IL_0053 -IL_003d: ldloc.0 IL_003e: ldloc.s V_4 IL_0040: ldloc.s V_5 IL_0042: ldloc.s V_6 IL_0044: call ""double[*,*,*].Get"" IL_0049: stloc.s V_7 -IL_004b: nop -IL_004c: nop ~IL_004d: ldloc.s V_6 IL_004f: ldc.i4.1 IL_0050: add IL_0051: stloc.s V_6 -IL_0053: ldloc.s V_6 IL_0055: ldloc.3 IL_0056: ble.s IL_003d ~IL_0058: ldloc.s V_5 IL_005a: ldc.i4.1 IL_005b: add IL_005c: stloc.s V_5 -IL_005e: ldloc.s V_5 IL_0060: ldloc.2 IL_0061: ble.s IL_0032 ~IL_0063: ldloc.s V_4 IL_0065: ldc.i4.1 IL_0066: add IL_0067: stloc.s V_4 -IL_0069: ldloc.s V_4 IL_006b: ldloc.1 IL_006c: ble.s IL_0027 -IL_006e: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 111 (0x6f) .maxstack 4 .locals init (double[,,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, int V_6, double V_7) //x -IL_0000: nop -IL_0001: nop -IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldc.i4.0 IL_0006: callvirt ""int System.Array.GetUpperBound(int)"" IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: callvirt ""int System.Array.GetUpperBound(int)"" IL_0013: stloc.2 IL_0014: ldloc.0 IL_0015: ldc.i4.2 IL_0016: callvirt ""int System.Array.GetUpperBound(int)"" IL_001b: stloc.3 IL_001c: ldloc.0 IL_001d: ldc.i4.0 IL_001e: callvirt ""int System.Array.GetLowerBound(int)"" IL_0023: stloc.s V_4 ~IL_0025: br.s IL_0069 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: callvirt ""int System.Array.GetLowerBound(int)"" IL_002e: stloc.s V_5 ~IL_0030: br.s IL_005e IL_0032: ldloc.0 IL_0033: ldc.i4.2 IL_0034: callvirt ""int System.Array.GetLowerBound(int)"" IL_0039: stloc.s V_6 ~IL_003b: br.s IL_0053 -IL_003d: ldloc.0 IL_003e: ldloc.s V_4 IL_0040: ldloc.s V_5 IL_0042: ldloc.s V_6 IL_0044: call ""double[*,*,*].Get"" IL_0049: stloc.s V_7 -IL_004b: nop -IL_004c: nop ~IL_004d: ldloc.s V_6 IL_004f: ldc.i4.1 IL_0050: add IL_0051: stloc.s V_6 -IL_0053: ldloc.s V_6 IL_0055: ldloc.3 IL_0056: ble.s IL_003d ~IL_0058: ldloc.s V_5 IL_005a: ldc.i4.1 IL_005b: add IL_005c: stloc.s V_5 -IL_005e: ldloc.s V_5 IL_0060: ldloc.2 IL_0061: ble.s IL_0032 ~IL_0063: ldloc.s V_4 IL_0065: ldc.i4.1 IL_0066: add IL_0067: stloc.s V_4 -IL_0069: ldloc.s V_4 IL_006b: ldloc.1 IL_006c: ble.s IL_0027 -IL_006e: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ForEachArray2() { var source = @"class C { static void M(string a, object[] b, double[,,] c) { foreach (var x in a) { foreach (var y in b) { } } foreach (var x in c) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 184 (0xb8) .maxstack 4 .locals init (string V_0, int V_1, char V_2, //x object[] V_3, int V_4, object V_5, //y double[,,] V_6, int V_7, int V_8, int V_9, int V_10, int V_11, int V_12, double V_13) //x IL_0000: nop IL_0001: nop IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldc.i4.0 IL_0005: stloc.1 IL_0006: br.s IL_0033 IL_0008: ldloc.0 IL_0009: ldloc.1 IL_000a: callvirt ""char string.this[int].get"" IL_000f: stloc.2 IL_0010: nop IL_0011: nop IL_0012: ldarg.1 IL_0013: stloc.3 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0027 IL_0019: ldloc.3 IL_001a: ldloc.s V_4 IL_001c: ldelem.ref IL_001d: stloc.s V_5 IL_001f: nop IL_0020: nop IL_0021: ldloc.s V_4 IL_0023: ldc.i4.1 IL_0024: add IL_0025: stloc.s V_4 IL_0027: ldloc.s V_4 IL_0029: ldloc.3 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0019 IL_002e: nop IL_002f: ldloc.1 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.1 IL_0033: ldloc.1 IL_0034: ldloc.0 IL_0035: callvirt ""int string.Length.get"" IL_003a: blt.s IL_0008 IL_003c: nop IL_003d: ldarg.2 IL_003e: stloc.s V_6 IL_0040: ldloc.s V_6 IL_0042: ldc.i4.0 IL_0043: callvirt ""int System.Array.GetUpperBound(int)"" IL_0048: stloc.s V_7 IL_004a: ldloc.s V_6 IL_004c: ldc.i4.1 IL_004d: callvirt ""int System.Array.GetUpperBound(int)"" IL_0052: stloc.s V_8 IL_0054: ldloc.s V_6 IL_0056: ldc.i4.2 IL_0057: callvirt ""int System.Array.GetUpperBound(int)"" IL_005c: stloc.s V_9 IL_005e: ldloc.s V_6 IL_0060: ldc.i4.0 IL_0061: callvirt ""int System.Array.GetLowerBound(int)"" IL_0066: stloc.s V_10 IL_0068: br.s IL_00b1 IL_006a: ldloc.s V_6 IL_006c: ldc.i4.1 IL_006d: callvirt ""int System.Array.GetLowerBound(int)"" IL_0072: stloc.s V_11 IL_0074: br.s IL_00a5 IL_0076: ldloc.s V_6 IL_0078: ldc.i4.2 IL_0079: callvirt ""int System.Array.GetLowerBound(int)"" IL_007e: stloc.s V_12 IL_0080: br.s IL_0099 IL_0082: ldloc.s V_6 IL_0084: ldloc.s V_10 IL_0086: ldloc.s V_11 IL_0088: ldloc.s V_12 IL_008a: call ""double[*,*,*].Get"" IL_008f: stloc.s V_13 IL_0091: nop IL_0092: nop IL_0093: ldloc.s V_12 IL_0095: ldc.i4.1 IL_0096: add IL_0097: stloc.s V_12 IL_0099: ldloc.s V_12 IL_009b: ldloc.s V_9 IL_009d: ble.s IL_0082 IL_009f: ldloc.s V_11 IL_00a1: ldc.i4.1 IL_00a2: add IL_00a3: stloc.s V_11 IL_00a5: ldloc.s V_11 IL_00a7: ldloc.s V_8 IL_00a9: ble.s IL_0076 IL_00ab: ldloc.s V_10 IL_00ad: ldc.i4.1 IL_00ae: add IL_00af: stloc.s V_10 IL_00b1: ldloc.s V_10 IL_00b3: ldloc.s V_7 IL_00b5: ble.s IL_006a IL_00b7: ret }"); } /// <summary> /// Unlike Dev12 we can handle array with more than 256 dimensions. /// </summary> [Fact] public void ForEachArray_ToManyDimensions() { var source = @"class C { static void M(object o) { foreach (var x in (object[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,])o) { } } }"; // Make sure the source contains an array with too many dimensions. var tooManyCommas = new string(',', 256); Assert.True(source.IndexOf(tooManyCommas, StringComparison.Ordinal) > 0); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); } [Fact] public void ForEachWithDynamicAndTuple() { var source = @"class C { static void M((dynamic, int) t) { foreach (var o in t.Item1) { } } }"; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 119 (0x77) .maxstack 3 .locals init (System.Collections.IEnumerator V_0, object V_1, //o [unchanged] V_2, System.IDisposable V_3) IL_0000: nop IL_0001: nop IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_0007: brfalse.s IL_000b IL_0009: br.s IL_002f IL_000b: ldc.i4.0 IL_000c: ldtoken ""System.Collections.IEnumerable"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldtoken ""C"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0025: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_002f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_0034: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>>.Target"" IL_0039: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_003e: ldarg.0 IL_003f: ldfld ""dynamic System.ValueTuple<dynamic, int>.Item1"" IL_0044: callvirt ""System.Collections.IEnumerable System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0049: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_004e: stloc.0 .try { IL_004f: br.s IL_005a IL_0051: ldloc.0 IL_0052: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0057: stloc.1 IL_0058: nop IL_0059: nop IL_005a: ldloc.0 IL_005b: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0060: brtrue.s IL_0051 IL_0062: leave.s IL_0076 } finally { IL_0064: ldloc.0 IL_0065: isinst ""System.IDisposable"" IL_006a: stloc.3 IL_006b: ldloc.3 IL_006c: brfalse.s IL_0075 IL_006e: ldloc.3 IL_006f: callvirt ""void System.IDisposable.Dispose()"" IL_0074: nop IL_0075: endfinally } IL_0076: ret }"); } [Fact] public void RemoveRestoreNullableAtArrayElement() { var source0 = MarkedSource( @"using System; class C { public static void M() { var <N:1>arr</N:1> = new string?[] { ""0"" }; <N:0>foreach</N:0> (var s in arr) { Console.WriteLine(1); } } }"); // Remove nullable var source1 = MarkedSource( @"using System; class C { public static void M() { var <N:1>arr</N:1> = new string[] { ""0"" }; <N:0>foreach</N:0> (var s in arr) { Console.WriteLine(1); } } }"); // Restore nullable var source2 = source0; var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: nop IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_0028 IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 IL_001b: nop IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: nop IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 IL_002e: ret }"); var compilation1 = CreateCompilation(source1.Tree, options: TestOptions.DebugDll); var compilation2 = compilation0.WithSource(source2.Tree); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: nop IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_0028 IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 IL_001b: nop IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: nop IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 IL_002e: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 -IL_0010: nop -IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 ~IL_0015: br.s IL_0028 -IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 -IL_001b: nop -IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop -IL_0023: nop ~IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 -IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 -IL_002e: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void AddAndDelete() { var source0 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { lock (F1()) { } foreach (var c in F2()) { } using (F3()) { } } }"; // Delete one statement. var source1 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { lock (F1()) { } foreach (var c in F2()) { } } }"; // Add statement with same temp kind. var source2 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { using (F3()) { } lock (F1()) { } foreach (var c in F2()) { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 93 (0x5d) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c System.IDisposable V_5) IL_0000: nop IL_0001: call ""object C.F1()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: nop IL_0022: call ""string C.F2()"" IL_0027: stloc.2 IL_0028: ldc.i4.0 IL_0029: stloc.3 IL_002a: br.s IL_003b IL_002c: ldloc.2 IL_002d: ldloc.3 IL_002e: callvirt ""char string.this[int].get"" IL_0033: stloc.s V_4 IL_0035: nop IL_0036: nop IL_0037: ldloc.3 IL_0038: ldc.i4.1 IL_0039: add IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldloc.2 IL_003d: callvirt ""int string.Length.get"" IL_0042: blt.s IL_002c IL_0044: call ""System.IDisposable C.F3()"" IL_0049: stloc.s V_5 .try { IL_004b: nop IL_004c: nop IL_004d: leave.s IL_005c } finally { IL_004f: ldloc.s V_5 IL_0051: brfalse.s IL_005b IL_0053: ldloc.s V_5 IL_0055: callvirt ""void System.IDisposable.Dispose()"" IL_005a: nop IL_005b: endfinally } IL_005c: ret }"); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var compilation2 = compilation0.WithSource(source2); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 69 (0x45) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c [unchanged] V_5) IL_0000: nop IL_0001: call ""object C.F1()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: nop IL_0022: call ""string C.F2()"" IL_0027: stloc.2 IL_0028: ldc.i4.0 IL_0029: stloc.3 IL_002a: br.s IL_003b IL_002c: ldloc.2 IL_002d: ldloc.3 IL_002e: callvirt ""char string.this[int].get"" IL_0033: stloc.s V_4 IL_0035: nop IL_0036: nop IL_0037: ldloc.3 IL_0038: ldc.i4.1 IL_0039: add IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldloc.2 IL_003d: callvirt ""int string.Length.get"" IL_0042: blt.s IL_002c IL_0044: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 93 (0x5d) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c [unchanged] V_5, System.IDisposable V_6) -IL_0000: nop -IL_0001: call ""System.IDisposable C.F3()"" IL_0006: stloc.s V_6 .try { -IL_0008: nop -IL_0009: nop IL_000a: leave.s IL_0019 } finally { ~IL_000c: ldloc.s V_6 IL_000e: brfalse.s IL_0018 IL_0010: ldloc.s V_6 IL_0012: callvirt ""void System.IDisposable.Dispose()"" IL_0017: nop ~IL_0018: endfinally } -IL_0019: call ""object C.F1()"" IL_001e: stloc.0 IL_001f: ldc.i4.0 IL_0020: stloc.1 .try { IL_0021: ldloc.0 IL_0022: ldloca.s V_1 IL_0024: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0029: nop -IL_002a: nop -IL_002b: nop IL_002c: leave.s IL_0039 } finally { ~IL_002e: ldloc.1 IL_002f: brfalse.s IL_0038 IL_0031: ldloc.0 IL_0032: call ""void System.Threading.Monitor.Exit(object)"" IL_0037: nop ~IL_0038: endfinally } -IL_0039: nop -IL_003a: call ""string C.F2()"" IL_003f: stloc.2 IL_0040: ldc.i4.0 IL_0041: stloc.3 ~IL_0042: br.s IL_0053 -IL_0044: ldloc.2 IL_0045: ldloc.3 IL_0046: callvirt ""char string.this[int].get"" IL_004b: stloc.s V_4 -IL_004d: nop -IL_004e: nop ~IL_004f: ldloc.3 IL_0050: ldc.i4.1 IL_0051: add IL_0052: stloc.3 -IL_0053: ldloc.3 IL_0054: ldloc.2 IL_0055: callvirt ""int string.Length.get"" IL_005a: blt.s IL_0044 -IL_005c: ret }", methodToken: diff2.EmitResult.UpdatedMethods.Single()); } [Fact] public void Insert() { var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } static void M() { lock (F1()) { } lock (F2()) { } } }"; var source1 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } static void M() { lock (F3()) { } // added lock (F1()) { } lock (F4()) { } // replaced } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Note that the order of unique ids in temporaries follows the // order of declaration in the updated method. Specifically, the // original temporary names (and unique ids) are not preserved. // (Should not be an issue since the names are used by EnC only.) diff1.VerifyIL("C.M", @"{ // Code size 108 (0x6c) .maxstack 2 .locals init (object V_0, bool V_1, [object] V_2, [bool] V_3, object V_4, bool V_5, object V_6, bool V_7) IL_0000: nop IL_0001: call ""object C.F3()"" IL_0006: stloc.s V_4 IL_0008: ldc.i4.0 IL_0009: stloc.s V_5 .try { IL_000b: ldloc.s V_4 IL_000d: ldloca.s V_5 IL_000f: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0014: nop IL_0015: nop IL_0016: nop IL_0017: leave.s IL_0026 } finally { IL_0019: ldloc.s V_5 IL_001b: brfalse.s IL_0025 IL_001d: ldloc.s V_4 IL_001f: call ""void System.Threading.Monitor.Exit(object)"" IL_0024: nop IL_0025: endfinally } IL_0026: call ""object C.F1()"" IL_002b: stloc.0 IL_002c: ldc.i4.0 IL_002d: stloc.1 .try { IL_002e: ldloc.0 IL_002f: ldloca.s V_1 IL_0031: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0036: nop IL_0037: nop IL_0038: nop IL_0039: leave.s IL_0046 } finally { IL_003b: ldloc.1 IL_003c: brfalse.s IL_0045 IL_003e: ldloc.0 IL_003f: call ""void System.Threading.Monitor.Exit(object)"" IL_0044: nop IL_0045: endfinally } IL_0046: call ""object C.F4()"" IL_004b: stloc.s V_6 IL_004d: ldc.i4.0 IL_004e: stloc.s V_7 .try { IL_0050: ldloc.s V_6 IL_0052: ldloca.s V_7 IL_0054: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0059: nop IL_005a: nop IL_005b: nop IL_005c: leave.s IL_006b } finally { IL_005e: ldloc.s V_7 IL_0060: brfalse.s IL_006a IL_0062: ldloc.s V_6 IL_0064: call ""void System.Threading.Monitor.Exit(object)"" IL_0069: nop IL_006a: endfinally } IL_006b: ret }"); } /// <summary> /// Should not reuse temporary locals /// having different temporary kinds. /// </summary> [Fact] public void NoReuseDifferentTempKind() { var source = @"class A : System.IDisposable { public object Current { get { return null; } } public bool MoveNext() { return false; } public void Dispose() { } internal int this[A a] { get { return 0; } set { } } } class B { public A GetEnumerator() { return null; } } class C { static A F() { return null; } static B G() { return null; } static void M(A a) { a[F()]++; using (F()) { } lock (F()) { } foreach (var o in G()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 137 (0x89) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, A V_2, A V_3, bool V_4, A V_5, object V_6, //o A V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""A C.F()"" IL_0007: stloc.s V_7 IL_0009: dup IL_000a: ldloc.s V_7 IL_000c: callvirt ""int A.this[A].get"" IL_0011: stloc.s V_8 IL_0013: ldloc.s V_7 IL_0015: ldloc.s V_8 IL_0017: ldc.i4.1 IL_0018: add IL_0019: callvirt ""void A.this[A].set"" IL_001e: nop IL_001f: call ""A C.F()"" IL_0024: stloc.2 .try { IL_0025: nop IL_0026: nop IL_0027: leave.s IL_0034 } finally { IL_0029: ldloc.2 IL_002a: brfalse.s IL_0033 IL_002c: ldloc.2 IL_002d: callvirt ""void System.IDisposable.Dispose()"" IL_0032: nop IL_0033: endfinally } IL_0034: call ""A C.F()"" IL_0039: stloc.3 IL_003a: ldc.i4.0 IL_003b: stloc.s V_4 .try { IL_003d: ldloc.3 IL_003e: ldloca.s V_4 IL_0040: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0045: nop IL_0046: nop IL_0047: nop IL_0048: leave.s IL_0056 } finally { IL_004a: ldloc.s V_4 IL_004c: brfalse.s IL_0055 IL_004e: ldloc.3 IL_004f: call ""void System.Threading.Monitor.Exit(object)"" IL_0054: nop IL_0055: endfinally } IL_0056: nop IL_0057: call ""B C.G()"" IL_005c: callvirt ""A B.GetEnumerator()"" IL_0061: stloc.s V_5 .try { IL_0063: br.s IL_0070 IL_0065: ldloc.s V_5 IL_0067: callvirt ""object A.Current.get"" IL_006c: stloc.s V_6 IL_006e: nop IL_006f: nop IL_0070: ldloc.s V_5 IL_0072: callvirt ""bool A.MoveNext()"" IL_0077: brtrue.s IL_0065 IL_0079: leave.s IL_0088 } finally { IL_007b: ldloc.s V_5 IL_007d: brfalse.s IL_0087 IL_007f: ldloc.s V_5 IL_0081: callvirt ""void System.IDisposable.Dispose()"" IL_0086: nop IL_0087: endfinally } IL_0088: ret }"); } [Fact] public void Switch_String() { var source0 = @"class C { static string F() { return null; } static void M() { switch (F()) { case ""a"": System.Console.WriteLine(1); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var source1 = @"class C { static string F() { return null; } static void M() { switch (F()) { case ""a"": System.Console.WriteLine(10); break; case ""b"": System.Console.WriteLine(20); break; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); // Validate presence of a hidden sequence point @IL_0007 that is required for proper function remapping. v0.VerifyIL("C.M", @" { // Code size 56 (0x38) .maxstack 2 .locals init (string V_0, string V_1) -IL_0000: nop -IL_0001: call ""string C.F()"" IL_0006: stloc.1 ~IL_0007: ldloc.1 IL_0008: stloc.0 ~IL_0009: ldloc.0 IL_000a: ldstr ""a"" IL_000f: call ""bool string.op_Equality(string, string)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldstr ""b"" IL_001c: call ""bool string.op_Equality(string, string)"" IL_0021: brtrue.s IL_002e IL_0023: br.s IL_0037 -IL_0025: ldc.i4.1 IL_0026: call ""void System.Console.WriteLine(int)"" IL_002b: nop -IL_002c: br.s IL_0037 -IL_002e: ldc.i4.2 IL_002f: call ""void System.Console.WriteLine(int)"" IL_0034: nop -IL_0035: br.s IL_0037 -IL_0037: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.SwitchStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 58 (0x3a) .maxstack 2 .locals init (string V_0, string V_1) -IL_0000: nop -IL_0001: call ""string C.F()"" IL_0006: stloc.1 ~IL_0007: ldloc.1 IL_0008: stloc.0 ~IL_0009: ldloc.0 IL_000a: ldstr ""a"" IL_000f: call ""bool string.op_Equality(string, string)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldstr ""b"" IL_001c: call ""bool string.op_Equality(string, string)"" IL_0021: brtrue.s IL_002f IL_0023: br.s IL_0039 -IL_0025: ldc.i4.s 10 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop -IL_002d: br.s IL_0039 -IL_002f: ldc.i4.s 20 IL_0031: call ""void System.Console.WriteLine(int)"" IL_0036: nop -IL_0037: br.s IL_0039 -IL_0039: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Switch_Integer() { var source0 = WithWindowsLineBreaks( @"class C { static int F() { return 1; } static void M() { switch (F()) { case 1: System.Console.WriteLine(1); break; case 2: System.Console.WriteLine(2); break; } } }"); var source1 = WithWindowsLineBreaks( @"class C { static int F() { return 1; } static void M() { switch (F()) { case 1: System.Console.WriteLine(10); break; case 2: System.Console.WriteLine(20); break; } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 40 (0x28) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: call ""int C.F()"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: ldc.i4.1 IL_000b: beq.s IL_0015 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ldc.i4.2 IL_0011: beq.s IL_001e IL_0013: br.s IL_0027 IL_0015: ldc.i4.1 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: br.s IL_0027 IL_001e: ldc.i4.2 IL_001f: call ""void System.Console.WriteLine(int)"" IL_0024: nop IL_0025: br.s IL_0027 IL_0027: ret }"); // Validate that we emit a hidden sequence point @IL_0007. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""21"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x9"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""49"" document=""1"" /> <entry offset=""0x1c"" startLine=""9"" startColumn=""50"" endLine=""9"" endColumn=""56"" document=""1"" /> <entry offset=""0x1e"" startLine=""10"" startColumn=""21"" endLine=""10"" endColumn=""49"" document=""1"" /> <entry offset=""0x25"" startLine=""10"" startColumn=""50"" endLine=""10"" endColumn=""56"" document=""1"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.SwitchStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: call ""int C.F()"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: ldc.i4.1 IL_000b: beq.s IL_0015 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ldc.i4.2 IL_0011: beq.s IL_001f IL_0013: br.s IL_0029 IL_0015: ldc.i4.s 10 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: br.s IL_0029 IL_001f: ldc.i4.s 20 IL_0021: call ""void System.Console.WriteLine(int)"" IL_0026: nop IL_0027: br.s IL_0029 IL_0029: ret }"); } [Fact] public void Switch_Patterns() { var source = WithWindowsLineBreaks(@" using static System.Console; class C { static object F() => 1; static bool P() => false; static void M() { switch (F()) { case 1: WriteLine(""int 1""); break; case byte b when P(): WriteLine(b); break; case int i when P(): WriteLine(i); break; case (byte)1: WriteLine(""byte 1""); break; case int j: WriteLine(j); break; case object o: WriteLine(o); break; } } }"); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""0"" offset=""106"" /> <slot kind=""0"" offset=""162"" /> <slot kind=""0"" offset=""273"" /> <slot kind=""0"" offset=""323"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>", options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints); v0.VerifyIL("C.M", @" { // Code size 147 (0x93) .maxstack 2 .locals init (byte V_0, //b int V_1, //i int V_2, //j object V_3, //o object V_4) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.s V_4 IL_0008: ldloc.s V_4 IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: isinst ""int"" IL_0011: brfalse.s IL_0020 IL_0013: ldloc.3 IL_0014: unbox.any ""int"" IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: beq.s IL_003c IL_001e: br.s IL_005b IL_0020: ldloc.3 IL_0021: isinst ""byte"" IL_0026: brfalse.s IL_0037 IL_0028: ldloc.3 IL_0029: unbox.any ""byte"" IL_002e: stloc.0 IL_002f: br.s IL_0049 IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: beq.s IL_006d IL_0035: br.s IL_0087 IL_0037: ldloc.3 IL_0038: brtrue.s IL_0087 IL_003a: br.s IL_0092 IL_003c: ldstr ""int 1"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: nop IL_0047: br.s IL_0092 IL_0049: call ""bool C.P()"" IL_004e: brtrue.s IL_0052 IL_0050: br.s IL_0031 IL_0052: ldloc.0 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: br.s IL_0092 IL_005b: call ""bool C.P()"" IL_0060: brtrue.s IL_0064 IL_0062: br.s IL_007a IL_0064: ldloc.1 IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: nop IL_006b: br.s IL_0092 IL_006d: ldstr ""byte 1"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: nop IL_0078: br.s IL_0092 IL_007a: ldloc.1 IL_007b: stloc.2 IL_007c: br.s IL_007e IL_007e: ldloc.2 IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: nop IL_0085: br.s IL_0092 IL_0087: br.s IL_0089 IL_0089: ldloc.3 IL_008a: call ""void System.Console.WriteLine(object)"" IL_008f: nop IL_0090: br.s IL_0092 IL_0092: ret }"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 147 (0x93) .maxstack 2 .locals init (byte V_0, //b int V_1, //i int V_2, //j object V_3, //o object V_4) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.s V_4 IL_0008: ldloc.s V_4 IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: isinst ""int"" IL_0011: brfalse.s IL_0020 IL_0013: ldloc.3 IL_0014: unbox.any ""int"" IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: beq.s IL_003c IL_001e: br.s IL_005b IL_0020: ldloc.3 IL_0021: isinst ""byte"" IL_0026: brfalse.s IL_0037 IL_0028: ldloc.3 IL_0029: unbox.any ""byte"" IL_002e: stloc.0 IL_002f: br.s IL_0049 IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: beq.s IL_006d IL_0035: br.s IL_0087 IL_0037: ldloc.3 IL_0038: brtrue.s IL_0087 IL_003a: br.s IL_0092 IL_003c: ldstr ""int 1"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: nop IL_0047: br.s IL_0092 IL_0049: call ""bool C.P()"" IL_004e: brtrue.s IL_0052 IL_0050: br.s IL_0031 IL_0052: ldloc.0 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: br.s IL_0092 IL_005b: call ""bool C.P()"" IL_0060: brtrue.s IL_0064 IL_0062: br.s IL_007a IL_0064: ldloc.1 IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: nop IL_006b: br.s IL_0092 IL_006d: ldstr ""byte 1"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: nop IL_0078: br.s IL_0092 IL_007a: ldloc.1 IL_007b: stloc.2 IL_007c: br.s IL_007e IL_007e: ldloc.2 IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: nop IL_0085: br.s IL_0092 IL_0087: br.s IL_0089 IL_0089: ldloc.3 IL_008a: call ""void System.Console.WriteLine(object)"" IL_008f: nop IL_0090: br.s IL_0092 IL_0092: ret }"); } [Fact] public void If() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { if (F()) { System.Console.WriteLine(1); } } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { if (F()) { System.Console.WriteLine(10); } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: call ""bool C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0013 IL_000a: nop IL_000b: ldc.i4.1 IL_000c: call ""void System.Console.WriteLine(int)"" IL_0011: nop IL_0012: nop IL_0013: ret } "); // Validate presence of a hidden sequence point @IL_0007 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x12"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x13"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.IfStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 21 (0x15) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: call ""bool C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0014 IL_000a: nop IL_000b: ldc.i4.s 10 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: nop IL_0014: ret }"); } [Fact] public void While() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { while (F()) { System.Console.WriteLine(1); } } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { while (F()) { System.Console.WriteLine(10); } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: br.s IL_000c IL_0003: nop IL_0004: ldc.i4.1 IL_0005: call ""void System.Console.WriteLine(int)"" IL_000a: nop IL_000b: nop IL_000c: call ""bool C.F()"" IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: brtrue.s IL_0003 IL_0015: ret } "); // Validate presence of a hidden sequence point @IL_0012 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0xb"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xc"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""20"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.WhileStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: br.s IL_000d IL_0003: nop IL_0004: ldc.i4.s 10 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: nop IL_000d: call ""bool C.F()"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: brtrue.s IL_0003 IL_0016: ret }"); } [Fact] public void Do1() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { do { System.Console.WriteLine(1); } while (F()); } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { do { System.Console.WriteLine(10); } while (F()); } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: nop IL_0002: ldc.i4.1 IL_0003: call ""void System.Console.WriteLine(int)"" IL_0008: nop IL_0009: nop IL_000a: call ""bool C.F()"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: brtrue.s IL_0001 IL_0013: ret }"); // Validate presence of a hidden sequence point @IL_0010 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x9"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""21"" document=""1"" /> <entry offset=""0x10"" hidden=""true"" document=""1"" /> <entry offset=""0x13"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.DoStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 21 (0x15) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: nop IL_0002: ldc.i4.s 10 IL_0004: call ""void System.Console.WriteLine(int)"" IL_0009: nop IL_000a: nop IL_000b: call ""bool C.F()"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: brtrue.s IL_0001 IL_0014: ret }"); } [Fact] public void For() { var source0 = @" class C { static bool F(int i) { return true; } static void G(int i) { } static void M() { for (int i = 1; F(i); G(i)) { System.Console.WriteLine(1); } } }"; var source1 = @" class C { static bool F(int i) { return true; } static void G(int i) { } static void M() { for (int i = 1; F(i); G(i)) { System.Console.WriteLine(10); } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); // Validate presence of a hidden sequence point @IL_001c that is required for proper function remapping. v0.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 1 .locals init (int V_0, //i bool V_1) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 ~IL_0003: br.s IL_0015 -IL_0005: nop -IL_0006: ldc.i4.1 IL_0007: call ""void System.Console.WriteLine(int)"" IL_000c: nop -IL_000d: nop -IL_000e: ldloc.0 IL_000f: call ""void C.G(int)"" IL_0014: nop -IL_0015: ldloc.0 IL_0016: call ""bool C.F(int)"" IL_001b: stloc.1 ~IL_001c: ldloc.1 IL_001d: brtrue.s IL_0005 -IL_001f: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.ForStatement, SyntaxKind.VariableDeclarator), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, //i bool V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: br.s IL_0016 IL_0005: nop IL_0006: ldc.i4.s 10 IL_0008: call ""void System.Console.WriteLine(int)"" IL_000d: nop IL_000e: nop IL_000f: ldloc.0 IL_0010: call ""void C.G(int)"" IL_0015: nop IL_0016: ldloc.0 IL_0017: call ""bool C.F(int)"" IL_001c: stloc.1 IL_001d: ldloc.1 IL_001e: brtrue.s IL_0005 IL_0020: ret } "); } [Fact] public void SynthesizedVariablesInLambdas1() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { var f = new System.Action(() => { lock (F()) { } }); } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<>c.<M>b__1_0()", @" { // Code size 34 (0x22) .maxstack 2 .locals init (object V_0, bool V_1) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: ret }"); #if TODO // identify the lambda in a semantic edit var methodData0 = v0.TestData.GetMethodData("C.<M>b__0"); var method0 = compilation0.GetMember<MethodSymbol>("C.<M>b__0"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("C.<M>b__0"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.<M>b__0", @" ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void SynthesizedVariablesInLambdas2() { var source0 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(1); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var source1 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(10); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var source2 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(100); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <M>b__0_0, <M>b__0_1}"); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <M>b__0_0, <M>b__0_1}"); var expectedIL = @" { // Code size 33 (0x21) .maxstack 2 .locals init (int[] V_0, int V_1, int V_2) //x IL_0000: nop IL_0001: nop IL_0002: ldarg.1 IL_0003: stloc.0 IL_0004: ldc.i4.0 IL_0005: stloc.1 IL_0006: br.s IL_001a IL_0008: ldloc.0 IL_0009: ldloc.1 IL_000a: ldelem.i4 IL_000b: stloc.2 IL_000c: nop IL_000d: ldc.i4.s 20 IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: nop IL_0016: ldloc.1 IL_0017: ldc.i4.1 IL_0018: add IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldloc.0 IL_001c: ldlen IL_001d: conv.i4 IL_001e: blt.s IL_0008 IL_0020: ret }"; diff1.VerifyIL(@"C.<>c.<M>b__0_1", expectedIL); diff2.VerifyIL(@"C.<>c.<M>b__0_1", expectedIL); } [Fact] public void SynthesizedVariablesInIterator1() { var source = @" using System.Collections.Generic; class C { public IEnumerable<int> F() { lock (F()) { } yield return 1; } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 131 (0x83) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_007a IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldarg.0 IL_0022: ldfld ""C C.<F>d__0.<>4__this"" IL_0027: call ""System.Collections.Generic.IEnumerable<int> C.F()"" IL_002c: stfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_0031: ldarg.0 IL_0032: ldc.i4.0 IL_0033: stfld ""bool C.<F>d__0.<>s__2"" .try { IL_0038: ldarg.0 IL_0039: ldfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_003e: ldarg.0 IL_003f: ldflda ""bool C.<F>d__0.<>s__2"" IL_0044: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0049: nop IL_004a: nop IL_004b: nop IL_004c: leave.s IL_0063 } finally { IL_004e: ldarg.0 IL_004f: ldfld ""bool C.<F>d__0.<>s__2"" IL_0054: brfalse.s IL_0062 IL_0056: ldarg.0 IL_0057: ldfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_005c: call ""void System.Threading.Monitor.Exit(object)"" IL_0061: nop IL_0062: endfinally } IL_0063: ldarg.0 IL_0064: ldnull IL_0065: stfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_006a: ldarg.0 IL_006b: ldc.i4.1 IL_006c: stfld ""int C.<F>d__0.<>2__current"" IL_0071: ldarg.0 IL_0072: ldc.i4.1 IL_0073: stfld ""int C.<F>d__0.<>1__state"" IL_0078: ldc.i4.1 IL_0079: ret IL_007a: ldarg.0 IL_007b: ldc.i4.m1 IL_007c: stfld ""int C.<F>d__0.<>1__state"" IL_0081: ldc.i4.0 IL_0082: ret }"); #if TODO var methodData0 = v0.TestData.GetMethodData("?"); var method0 = compilation0.GetMember<MethodSymbol>("?"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("?"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("?", @" {", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void SynthesizedVariablesInAsyncMethod1() { var source = @" using System.Threading.Tasks; class C { public async Task<int> F() { lock (F()) { } await F(); return 1; } } "; var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 246 (0xf6) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, C.<F>d__0 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_0011 IL_000c: br IL_009e -IL_0011: nop -IL_0012: ldarg.0 IL_0013: ldarg.0 IL_0014: ldfld ""C C.<F>d__0.<>4__this"" IL_0019: call ""System.Threading.Tasks.Task<int> C.F()"" IL_001e: stfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: stfld ""bool C.<F>d__0.<>s__2"" .try { IL_002a: ldarg.0 IL_002b: ldfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0030: ldarg.0 IL_0031: ldflda ""bool C.<F>d__0.<>s__2"" IL_0036: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_003b: nop -IL_003c: nop -IL_003d: nop IL_003e: leave.s IL_0059 } finally { ~IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: bge.s IL_0058 IL_0044: ldarg.0 IL_0045: ldfld ""bool C.<F>d__0.<>s__2"" IL_004a: brfalse.s IL_0058 IL_004c: ldarg.0 IL_004d: ldfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0052: call ""void System.Threading.Monitor.Exit(object)"" IL_0057: nop ~IL_0058: endfinally } ~IL_0059: ldarg.0 IL_005a: ldnull IL_005b: stfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" -IL_0060: ldarg.0 IL_0061: ldfld ""C C.<F>d__0.<>4__this"" IL_0066: call ""System.Threading.Tasks.Task<int> C.F()"" IL_006b: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0070: stloc.2 ~IL_0071: ldloca.s V_2 IL_0073: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0078: brtrue.s IL_00ba IL_007a: ldarg.0 IL_007b: ldc.i4.0 IL_007c: dup IL_007d: stloc.0 IL_007e: stfld ""int C.<F>d__0.<>1__state"" <IL_0083: ldarg.0 IL_0084: ldloc.2 IL_0085: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_008a: ldarg.0 IL_008b: stloc.3 IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0092: ldloca.s V_2 IL_0094: ldloca.s V_3 IL_0096: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)"" IL_009b: nop IL_009c: leave.s IL_00f5 >IL_009e: ldarg.0 IL_009f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_00a4: stloc.2 IL_00a5: ldarg.0 IL_00a6: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_00ab: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00b1: ldarg.0 IL_00b2: ldc.i4.m1 IL_00b3: dup IL_00b4: stloc.0 IL_00b5: stfld ""int C.<F>d__0.<>1__state"" IL_00ba: ldloca.s V_2 IL_00bc: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00c1: pop -IL_00c2: ldc.i4.1 IL_00c3: stloc.1 IL_00c4: leave.s IL_00e0 } catch System.Exception { ~IL_00c6: stloc.s V_4 IL_00c8: ldarg.0 IL_00c9: ldc.i4.s -2 IL_00cb: stfld ""int C.<F>d__0.<>1__state"" IL_00d0: ldarg.0 IL_00d1: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00d6: ldloc.s V_4 IL_00d8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00dd: nop IL_00de: leave.s IL_00f5 } -IL_00e0: ldarg.0 IL_00e1: ldc.i4.s -2 IL_00e3: stfld ""int C.<F>d__0.<>1__state"" ~IL_00e8: ldarg.0 IL_00e9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00ee: ldloc.1 IL_00ef: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00f4: nop IL_00f5: ret }", sequencePoints: "C+<F>d__0.MoveNext"); #if TODO var methodData0 = v0.TestData.GetMethodData("?"); var method0 = compilation0.GetMember<MethodSymbol>("?"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("?"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("?", @" {", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void OutVar() { var source = @" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int x, out var y); return x + y; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop -IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 -IL_0011: ldloc.3 IL_0012: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternVariable() { var source = @" class C { static int F(object o) { if (o is int i) { return i; } return 0; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 ~IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d -IL_0018: nop -IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0021 -IL_001d: ldc.i4.0 IL_001e: stloc.3 IL_001f: br.s IL_0021 -IL_0021: ldloc.3 IL_0022: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Tuple_Parenthesized() { var source = @" class C { static int F() { (int, (int, int)) x = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x [int] V_1, int V_2) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" -IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.2 IL_002f: br.s IL_0031 -IL_0031: ldloc.2 IL_0032: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Tuple_Decomposition() { var source = @" class C { static int F() { (int x, (int y, int z)) = (1, (2, 3)); return x + y + z; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z [int] V_3, int V_4) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 -IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.s V_4 IL_000e: br.s IL_0010 -IL_0010: ldloc.s V_4 IL_0012: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternMatching_Variable() { var source = @" class C { static int F(object o) { if (o is int i) { return i; } return 0; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 ~IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d -IL_0018: nop -IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0021 -IL_001d: ldc.i4.0 IL_001e: stloc.3 IL_001f: br.s IL_0021 -IL_0021: ldloc.3 IL_0022: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternMatching_NoVariable() { var source = @" class C { static int F(object o) { if ((o is bool) || (o is 0)) { return 0; } return 1; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (bool V_0, [int] V_1, int V_2) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brtrue.s IL_001f IL_0009: ldarg.0 IL_000a: isinst ""int"" IL_000f: brfalse.s IL_001c IL_0011: ldarg.0 IL_0012: unbox.any ""int"" IL_0017: ldc.i4.0 IL_0018: ceq IL_001a: br.s IL_001d IL_001c: ldc.i4.0 IL_001d: br.s IL_0020 IL_001f: ldc.i4.1 IL_0020: stloc.0 ~IL_0021: ldloc.0 IL_0022: brfalse.s IL_0029 -IL_0024: nop -IL_0025: ldc.i4.0 IL_0026: stloc.2 IL_0027: br.s IL_002d -IL_0029: ldc.i4.1 IL_002a: stloc.2 IL_002b: br.s IL_002d -IL_002d: ldloc.2 IL_002e: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void VarPattern() { var source = @" using System.Threading.Tasks; class C { static object G(object o1, object o2) { return (o1, o2) switch { (int a, string b) => a, _ => 0 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 62 (0x3e) .maxstack 1 .locals init (int V_0, //a string V_1, //b [int] V_2, [object] V_3, int V_4, object V_5) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 -IL_0004: nop ~IL_0005: ldarg.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0027 IL_000d: ldarg.0 IL_000e: unbox.any ""int"" IL_0013: stloc.0 ~IL_0014: ldarg.1 IL_0015: isinst ""string"" IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: brtrue.s IL_0020 IL_001e: br.s IL_0027 ~IL_0020: br.s IL_0022 -IL_0022: ldloc.0 IL_0023: stloc.s V_4 IL_0025: br.s IL_002c -IL_0027: ldc.i4.0 IL_0028: stloc.s V_4 IL_002a: br.s IL_002c ~IL_002c: ldc.i4.1 IL_002d: brtrue.s IL_0030 -IL_002f: nop ~IL_0030: ldloc.s V_4 IL_0032: box ""int"" IL_0037: stloc.s V_5 IL_0039: br.s IL_003b -IL_003b: ldloc.s V_5 IL_003d: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void RecursiveSwitchExpression() { var source = @" class C { static object G(object o) { return o switch { int i => i switch { 0 => 1, _ => 2, }, _ => 3 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 76 (0x4c) .maxstack 1 .locals init (int V_0, //i [int] V_1, [int] V_2, [object] V_3, int V_4, int V_5, object V_6) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 -IL_0004: nop ~IL_0005: ldarg.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0035 IL_000d: ldarg.0 IL_000e: unbox.any ""int"" IL_0013: stloc.0 ~IL_0014: br.s IL_0016 ~IL_0016: br.s IL_0018 IL_0018: ldc.i4.1 IL_0019: brtrue.s IL_001c -IL_001b: nop ~IL_001c: ldloc.0 IL_001d: brfalse.s IL_0021 IL_001f: br.s IL_0026 -IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b -IL_0026: ldc.i4.2 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b ~IL_002b: ldc.i4.1 IL_002c: brtrue.s IL_002f -IL_002e: nop -IL_002f: ldloc.s V_5 IL_0031: stloc.s V_4 IL_0033: br.s IL_003a -IL_0035: ldc.i4.3 IL_0036: stloc.s V_4 IL_0038: br.s IL_003a ~IL_003a: ldc.i4.1 IL_003b: brtrue.s IL_003e -IL_003d: nop ~IL_003e: ldloc.s V_4 IL_0040: box ""int"" IL_0045: stloc.s V_6 IL_0047: br.s IL_0049 -IL_0049: ldloc.s V_6 IL_004b: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void RecursiveSwitchExpressionWithAwait() { var source = @" using System.Threading.Tasks; class C { static async Task<object> G(object o) { return o switch { Task<int> i when await i > 0 => await i switch { 1 => 1, _ => 2, }, _ => 3 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetEquivalentNodesMap(g1, g0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 56 (0x38) .maxstack 2 .locals init (C.<G>d__0 V_0) ~IL_0000: newobj ""C.<G>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 ~IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""object C.<G>d__0.o"" IL_0018: ldloc.0 -IL_0019: ldc.i4.m1 -IL_001a: stfld ""int C.<G>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<C.<G>d__0>(ref C.<G>d__0)"" IL_002c: ldloc.0 IL_002d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0032: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0037: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void SwitchExpressionInsideAwait() { var source = @" using System.Threading.Tasks; class C { static async Task<object> G(Task<object> o) { return await o switch { int i => 0, _ => 1 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 56 (0x38) .maxstack 2 .locals init (C.<G>d__0 V_0) ~IL_0000: newobj ""C.<G>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 ~IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""System.Threading.Tasks.Task<object> C.<G>d__0.o"" IL_0018: ldloc.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<G>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<C.<G>d__0>(ref C.<G>d__0)"" IL_002c: ldloc.0 <IL_002d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0032: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0037: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void SwitchExpressionWithOutVar() { var source = @" class C { static object G() { return N(out var x) switch { null => x switch {1 => 1, _ => 2 }, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 73 (0x49) .maxstack 2 .locals init (int V_0, //x [int] V_1, [object] V_2, [int] V_3, [object] V_4, int V_5, object V_6, int V_7, object V_8) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: call ""object C.N(out int)"" IL_0008: stloc.s V_6 IL_000a: ldc.i4.1 IL_000b: brtrue.s IL_000e -IL_000d: nop ~IL_000e: ldloc.s V_6 IL_0010: brfalse.s IL_0014 IL_0012: br.s IL_0032 ~IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 -IL_0017: nop ~IL_0018: ldloc.0 IL_0019: ldc.i4.1 IL_001a: beq.s IL_001e IL_001c: br.s IL_0023 -IL_001e: ldc.i4.1 IL_001f: stloc.s V_7 IL_0021: br.s IL_0028 -IL_0023: ldc.i4.2 IL_0024: stloc.s V_7 IL_0026: br.s IL_0028 ~IL_0028: ldc.i4.1 IL_0029: brtrue.s IL_002c -IL_002b: nop -IL_002c: ldloc.s V_7 IL_002e: stloc.s V_5 IL_0030: br.s IL_0037 -IL_0032: ldc.i4.1 IL_0033: stloc.s V_5 IL_0035: br.s IL_0037 ~IL_0037: ldc.i4.1 IL_0038: brtrue.s IL_003b -IL_003a: nop ~IL_003b: ldloc.s V_5 IL_003d: box ""int"" IL_0042: stloc.s V_8 IL_0044: br.s IL_0046 -IL_0046: ldloc.s V_8 IL_0048: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ForEachStatement_Deconstruction() { var source = @" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (x, (y, z)) in F()) { System.Console.WriteLine(x); } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) -IL_0000: nop -IL_0001: nop -IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 ~IL_000c: br.s IL_0045 -IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 -IL_0036: nop -IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop -IL_003e: nop ~IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 -IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e -IL_004d: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ComplexTypes() { var sourceText = @" using System; using System.Collections.Generic; class C1<T> { public enum E { A } } class C { public unsafe static void G() { var <N:0>a</N:0> = new { key = ""a"", value = new List<(int, int)>()}; var <N:1>b</N:1> = (number: 5, value: a); var <N:2>c</N:2> = new[] { b }; int[] <N:3>array</N:3> = { 1, 2, 3 }; ref int <N:4>d</N:4> = ref array[0]; ref readonly int <N:5>e</N:5> = ref array[0]; C1<(int, dynamic)>.E***[,,] <N:6>x</N:6> = null; var <N:7>f</N:7> = new List<string?>(); } } "; var source0 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var source1 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var source2 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithAllowUnsafe(true)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 88 (0x58) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_0035: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldc.i4.0 IL_003d: ldelema ""int"" IL_0042: stloc.s V_4 IL_0044: ldloc.3 IL_0045: ldc.i4.0 IL_0046: ldelema ""int"" IL_004b: stloc.s V_5 IL_004d: ldnull IL_004e: stloc.s V_6 IL_0050: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0055: stloc.s V_7 IL_0057: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 89 (0x59) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldc.i4.0 IL_0031: ldc.i4.1 IL_0032: stelem.i4 IL_0033: dup IL_0034: ldc.i4.1 IL_0035: ldc.i4.2 IL_0036: stelem.i4 IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.3 IL_003a: stelem.i4 IL_003b: stloc.3 IL_003c: ldloc.3 IL_003d: ldc.i4.0 IL_003e: ldelema ""int"" IL_0043: stloc.s V_4 IL_0045: ldloc.3 IL_0046: ldc.i4.0 IL_0047: ldelema ""int"" IL_004c: stloc.s V_5 IL_004e: ldnull IL_004f: stloc.s V_6 IL_0051: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0056: stloc.s V_7 IL_0058: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 89 (0x59) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldc.i4.0 IL_0031: ldc.i4.1 IL_0032: stelem.i4 IL_0033: dup IL_0034: ldc.i4.1 IL_0035: ldc.i4.2 IL_0036: stelem.i4 IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.3 IL_003a: stelem.i4 IL_003b: stloc.3 IL_003c: ldloc.3 IL_003d: ldc.i4.0 IL_003e: ldelema ""int"" IL_0043: stloc.s V_4 IL_0045: ldloc.3 IL_0046: ldc.i4.0 IL_0047: ldelema ""int"" IL_004c: stloc.s V_5 IL_004e: ldnull IL_004f: stloc.s V_6 IL_0051: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0056: stloc.s V_7 IL_0058: ret } "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader.Tools; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class LocalSlotMappingTests : EditAndContinueTestBase { /// <summary> /// If no changes were made we don't produce a syntax map. /// If we don't have syntax map and preserve variables is true we should still successfully map the locals to their previous slots. /// </summary> [Fact] public void SlotMappingWithNoChanges() { var source0 = @" using System; class C { static void Main(string[] args) { var b = true; do { Console.WriteLine(""hi""); } while (b == true); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source0); var v0 = CompileAndVerify(compilation0); var methodData0 = v0.TestData.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); v0.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0, //b bool V_1) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 -IL_0003: nop -IL_0004: ldstr ""hi"" IL_0009: call ""void System.Console.WriteLine(string)"" IL_000e: nop -IL_000f: nop -IL_0010: ldloc.0 IL_0011: stloc.1 ~IL_0012: ldloc.1 IL_0013: brtrue.s IL_0003 -IL_0015: ret }", sequencePoints: "C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, syntaxMap: null, preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0, //b bool V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: nop IL_0004: ldstr ""hi"" IL_0009: call ""void System.Console.WriteLine(string)"" IL_000e: nop IL_000f: nop IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldloc.1 IL_0013: brtrue.s IL_0003 IL_0015: ret }"); } [Fact] public void OutOfOrderUserLocals() { var source = WithWindowsLineBreaks(@" using System; public class C { public static void M() { for (int i = 1; i < 1; i++) Console.WriteLine(1); for (int i = 1; i < 2; i++) Console.WriteLine(2); int j; for (j = 1; j < 3; j++) Console.WriteLine(3); } }"); var compilation0 = CreateCompilation(source, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 75 (0x4b) .maxstack 2 .locals init (int V_0, //j int V_1, //i bool V_2, int V_3, //i bool V_4, bool V_5) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: br.s IL_0010 IL_0005: ldc.i4.1 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: ldloc.1 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.1 IL_0012: clt IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: brtrue.s IL_0005 IL_0018: ldc.i4.1 IL_0019: stloc.3 IL_001a: br.s IL_0027 IL_001c: ldc.i4.2 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: ldloc.3 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.3 IL_0027: ldloc.3 IL_0028: ldc.i4.2 IL_0029: clt IL_002b: stloc.s V_4 IL_002d: ldloc.s V_4 IL_002f: brtrue.s IL_001c IL_0031: ldc.i4.1 IL_0032: stloc.0 IL_0033: br.s IL_0040 IL_0035: ldc.i4.3 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldc.i4.1 IL_003e: add IL_003f: stloc.0 IL_0040: ldloc.0 IL_0041: ldc.i4.3 IL_0042: clt IL_0044: stloc.s V_5 IL_0046: ldloc.s V_5 IL_0048: brtrue.s IL_0035 IL_004a: ret } "); v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""135"" /> <slot kind=""0"" offset=""20"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""0"" offset=""79"" /> <slot kind=""1"" offset=""70"" /> <slot kind=""1"" offset=""147"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""14"" endLine=""8"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""8"" startColumn=""37"" endLine=""8"" endColumn=""58"" document=""1"" /> <entry offset=""0xc"" startLine=""8"" startColumn=""32"" endLine=""8"" endColumn=""35"" document=""1"" /> <entry offset=""0x10"" startLine=""8"" startColumn=""25"" endLine=""8"" endColumn=""30"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x18"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""9"" startColumn=""37"" endLine=""9"" endColumn=""58"" document=""1"" /> <entry offset=""0x23"" startLine=""9"" startColumn=""32"" endLine=""9"" endColumn=""35"" document=""1"" /> <entry offset=""0x27"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x2d"" hidden=""true"" document=""1"" /> <entry offset=""0x31"" startLine=""12"" startColumn=""14"" endLine=""12"" endColumn=""19"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" startLine=""12"" startColumn=""33"" endLine=""12"" endColumn=""54"" document=""1"" /> <entry offset=""0x3c"" startLine=""12"" startColumn=""28"" endLine=""12"" endColumn=""31"" document=""1"" /> <entry offset=""0x40"" startLine=""12"" startColumn=""21"" endLine=""12"" endColumn=""26"" document=""1"" /> <entry offset=""0x46"" hidden=""true"" document=""1"" /> <entry offset=""0x4a"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4b""> <namespace name=""System"" /> <local name=""j"" il_index=""0"" il_start=""0x0"" il_end=""0x4b"" attributes=""0"" /> <scope startOffset=""0x1"" endOffset=""0x18""> <local name=""i"" il_index=""1"" il_start=""0x1"" il_end=""0x18"" attributes=""0"" /> </scope> <scope startOffset=""0x18"" endOffset=""0x31""> <local name=""i"" il_index=""3"" il_start=""0x18"" il_end=""0x31"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); var symReader = v0.CreateSymReader(); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), symReader.GetEncMethodDebugInfo); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // check that all user-defined and long-lived synthesized local slots are reused diff1.VerifyIL("C.M", @" { // Code size 75 (0x4b) .maxstack 2 .locals init (int V_0, //j int V_1, //i bool V_2, int V_3, //i bool V_4, bool V_5) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: br.s IL_0010 IL_0005: ldc.i4.1 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: ldloc.1 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.1 IL_0012: clt IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: brtrue.s IL_0005 IL_0018: ldc.i4.1 IL_0019: stloc.3 IL_001a: br.s IL_0027 IL_001c: ldc.i4.2 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: ldloc.3 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.3 IL_0027: ldloc.3 IL_0028: ldc.i4.2 IL_0029: clt IL_002b: stloc.s V_4 IL_002d: ldloc.s V_4 IL_002f: brtrue.s IL_001c IL_0031: ldc.i4.1 IL_0032: stloc.0 IL_0033: br.s IL_0040 IL_0035: ldc.i4.3 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldc.i4.1 IL_003e: add IL_003f: stloc.0 IL_0040: ldloc.0 IL_0041: ldc.i4.3 IL_0042: clt IL_0044: stloc.s V_5 IL_0046: ldloc.s V_5 IL_0048: brtrue.s IL_0035 IL_004a: ret } "); } /// <summary> /// Enc debug info is only present in debug builds. /// </summary> [Fact] public void DebugOnly() { var source = WithWindowsLineBreaks( @"class C { static System.IDisposable F() { return null; } static void M() { lock (F()) { } using (F()) { } } }"); var debug = CreateCompilation(source, options: TestOptions.DebugDll); var release = CreateCompilation(source, options: TestOptions.ReleaseDll); CompileAndVerify(debug).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""3"" offset=""11"" /> <slot kind=""2"" offset=""11"" /> <slot kind=""4"" offset=""35"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""19"" document=""1"" /> <entry offset=""0x12"" startLine=""9"" startColumn=""20"" endLine=""9"" endColumn=""21"" document=""1"" /> <entry offset=""0x13"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x20"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x27"" startLine=""10"" startColumn=""21"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0x28"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); CompileAndVerify(release).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""19"" document=""1"" /> <entry offset=""0x10"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x22"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x24"" hidden=""true"" document=""1"" /> <entry offset=""0x2d"" hidden=""true"" document=""1"" /> <entry offset=""0x2e"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void Using() { var source = WithWindowsLineBreaks( @"class C : System.IDisposable { public void Dispose() { } static System.IDisposable F() { return new C(); } static void M() { using (F()) { using (var u = F()) { } using (F()) { } } } }"); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), m => methodData0.GetEncDebugInfo()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 65 (0x41) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1, //u System.IDisposable V_2) IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: call ""System.IDisposable C.F()"" IL_000d: stloc.1 .try { IL_000e: nop IL_000f: nop IL_0010: leave.s IL_001d } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001c IL_0015: ldloc.1 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } IL_001d: call ""System.IDisposable C.F()"" IL_0022: stloc.2 .try { IL_0023: nop IL_0024: nop IL_0025: leave.s IL_0032 } finally { IL_0027: ldloc.2 IL_0028: brfalse.s IL_0031 IL_002a: ldloc.2 IL_002b: callvirt ""void System.IDisposable.Dispose()"" IL_0030: nop IL_0031: endfinally } IL_0032: nop IL_0033: leave.s IL_0040 } finally { IL_0035: ldloc.0 IL_0036: brfalse.s IL_003f IL_0038: ldloc.0 IL_0039: callvirt ""void System.IDisposable.Dispose()"" IL_003e: nop IL_003f: endfinally } IL_0040: ret }"); } [Fact] public void Lock() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { lock (F()) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 66 (0x42) .maxstack 2 .locals init (object V_0, bool V_1, object V_2, bool V_3) -IL_0000: nop -IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop -IL_0012: nop -IL_0013: call ""object C.F()"" IL_0018: stloc.2 IL_0019: ldc.i4.0 IL_001a: stloc.3 .try { IL_001b: ldloc.2 IL_001c: ldloca.s V_3 IL_001e: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0023: nop -IL_0024: nop -IL_0025: nop IL_0026: leave.s IL_0033 } finally { ~IL_0028: ldloc.3 IL_0029: brfalse.s IL_0032 IL_002b: ldloc.2 IL_002c: call ""void System.Threading.Monitor.Exit(object)"" IL_0031: nop ~IL_0032: endfinally } -IL_0033: nop IL_0034: leave.s IL_0041 } finally { ~IL_0036: ldloc.1 IL_0037: brfalse.s IL_0040 IL_0039: ldloc.0 IL_003a: call ""void System.Threading.Monitor.Exit(object)"" IL_003f: nop ~IL_0040: endfinally } -IL_0041: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Using Monitor.Enter(object). /// </summary> [Fact] public void Lock_Pre40() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { } } }"; var compilation0 = CreateEmptyCompilation(source, options: TestOptions.DebugDll, references: new[] { MscorlibRef_v20 }); var compilation1 = CreateEmptyCompilation(source, options: TestOptions.DebugDll, references: new[] { MscorlibRef_v20 }); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 27 (0x1b) .maxstack 1 .locals init (object V_0) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void System.Threading.Monitor.Enter(object)"" IL_000d: nop .try { IL_000e: nop IL_000f: nop IL_0010: leave.s IL_001a } finally { IL_0012: ldloc.0 IL_0013: call ""void System.Threading.Monitor.Exit(object)"" IL_0018: nop IL_0019: endfinally } IL_001a: ret }"); } [Fact] public void Fixed() { var source = @"class C { unsafe static void M(string s, int[] i) { fixed (char *p = s) { fixed (int *q = i) { } fixed (char *r = s) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 81 (0x51) .maxstack 2 .locals init (char* V_0, //p pinned string V_1, int* V_2, //q [unchanged] V_3, char* V_4, //r pinned string V_5, pinned int[] V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.1 IL_0003: ldloc.1 IL_0004: conv.u IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0011 IL_0009: ldloc.0 IL_000a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_000f: add IL_0010: stloc.0 IL_0011: nop IL_0012: ldarg.1 IL_0013: dup IL_0014: stloc.s V_6 IL_0016: brfalse.s IL_001e IL_0018: ldloc.s V_6 IL_001a: ldlen IL_001b: conv.i4 IL_001c: brtrue.s IL_0023 IL_001e: ldc.i4.0 IL_001f: conv.u IL_0020: stloc.2 IL_0021: br.s IL_002d IL_0023: ldloc.s V_6 IL_0025: ldc.i4.0 IL_0026: ldelema ""int"" IL_002b: conv.u IL_002c: stloc.2 IL_002d: nop IL_002e: nop IL_002f: ldnull IL_0030: stloc.s V_6 IL_0032: ldarg.0 IL_0033: stloc.s V_5 IL_0035: ldloc.s V_5 IL_0037: conv.u IL_0038: stloc.s V_4 IL_003a: ldloc.s V_4 IL_003c: brfalse.s IL_0048 IL_003e: ldloc.s V_4 IL_0040: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_0045: add IL_0046: stloc.s V_4 IL_0048: nop IL_0049: nop IL_004a: ldnull IL_004b: stloc.s V_5 IL_004d: nop IL_004e: ldnull IL_004f: stloc.1 IL_0050: ret }"); } [WorkItem(770053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770053")] [Fact] public void FixedMultiple() { var source = @"class C { unsafe static void M(string s1, string s2, string s3, string s4) { fixed (char* p1 = s1, p2 = s2) { *p1 = *p2; } fixed (char* p1 = s1, p3 = s3, p2 = s4) { *p1 = *p2; *p2 = *p3; fixed (char *p4 = s2) { *p3 = *p4; } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 166 (0xa6) .maxstack 2 .locals init (char* V_0, //p1 char* V_1, //p2 pinned string V_2, pinned string V_3, char* V_4, //p1 char* V_5, //p3 char* V_6, //p2 pinned string V_7, pinned string V_8, pinned string V_9, char* V_10, //p4 pinned string V_11) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: conv.u IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0011 IL_0009: ldloc.0 IL_000a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_000f: add IL_0010: stloc.0 IL_0011: ldarg.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: conv.u IL_0015: stloc.1 IL_0016: ldloc.1 IL_0017: brfalse.s IL_0021 IL_0019: ldloc.1 IL_001a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_001f: add IL_0020: stloc.1 IL_0021: nop IL_0022: ldloc.0 IL_0023: ldloc.1 IL_0024: ldind.u2 IL_0025: stind.i2 IL_0026: nop IL_0027: ldnull IL_0028: stloc.2 IL_0029: ldnull IL_002a: stloc.3 IL_002b: ldarg.0 IL_002c: stloc.s V_7 IL_002e: ldloc.s V_7 IL_0030: conv.u IL_0031: stloc.s V_4 IL_0033: ldloc.s V_4 IL_0035: brfalse.s IL_0041 IL_0037: ldloc.s V_4 IL_0039: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_003e: add IL_003f: stloc.s V_4 IL_0041: ldarg.2 IL_0042: stloc.s V_8 IL_0044: ldloc.s V_8 IL_0046: conv.u IL_0047: stloc.s V_5 IL_0049: ldloc.s V_5 IL_004b: brfalse.s IL_0057 IL_004d: ldloc.s V_5 IL_004f: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_0054: add IL_0055: stloc.s V_5 IL_0057: ldarg.3 IL_0058: stloc.s V_9 IL_005a: ldloc.s V_9 IL_005c: conv.u IL_005d: stloc.s V_6 IL_005f: ldloc.s V_6 IL_0061: brfalse.s IL_006d IL_0063: ldloc.s V_6 IL_0065: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_006a: add IL_006b: stloc.s V_6 IL_006d: nop IL_006e: ldloc.s V_4 IL_0070: ldloc.s V_6 IL_0072: ldind.u2 IL_0073: stind.i2 IL_0074: ldloc.s V_6 IL_0076: ldloc.s V_5 IL_0078: ldind.u2 IL_0079: stind.i2 IL_007a: ldarg.1 IL_007b: stloc.s V_11 IL_007d: ldloc.s V_11 IL_007f: conv.u IL_0080: stloc.s V_10 IL_0082: ldloc.s V_10 IL_0084: brfalse.s IL_0090 IL_0086: ldloc.s V_10 IL_0088: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_008d: add IL_008e: stloc.s V_10 IL_0090: nop IL_0091: ldloc.s V_5 IL_0093: ldloc.s V_10 IL_0095: ldind.u2 IL_0096: stind.i2 IL_0097: nop IL_0098: ldnull IL_0099: stloc.s V_11 IL_009b: nop IL_009c: ldnull IL_009d: stloc.s V_7 IL_009f: ldnull IL_00a0: stloc.s V_8 IL_00a2: ldnull IL_00a3: stloc.s V_9 IL_00a5: ret } "); } [Fact] public void ForEach() { var source = @"using System.Collections; using System.Collections.Generic; class C { static IEnumerable F1() { return null; } static List<object> F2() { return null; } static IEnumerable F3() { return null; } static List<object> F4() { return null; } static void M() { foreach (var @x in F1()) { foreach (object y in F2()) { } } foreach (var x in F4()) { foreach (var y in F3()) { } foreach (var z in F2()) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 272 (0x110) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, object V_1, //x System.Collections.Generic.List<object>.Enumerator V_2, object V_3, //y [unchanged] V_4, System.Collections.Generic.List<object>.Enumerator V_5, object V_6, //x System.Collections.IEnumerator V_7, object V_8, //y System.Collections.Generic.List<object>.Enumerator V_9, object V_10, //z System.IDisposable V_11) IL_0000: nop IL_0001: nop IL_0002: call ""System.Collections.IEnumerable C.F1()"" IL_0007: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_000c: stloc.0 .try { IL_000d: br.s IL_004a IL_000f: ldloc.0 IL_0010: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0015: stloc.1 IL_0016: nop IL_0017: nop IL_0018: call ""System.Collections.Generic.List<object> C.F2()"" IL_001d: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_0022: stloc.2 .try { IL_0023: br.s IL_002f IL_0025: ldloca.s V_2 IL_0027: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_002c: stloc.3 IL_002d: nop IL_002e: nop IL_002f: ldloca.s V_2 IL_0031: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_0036: brtrue.s IL_0025 IL_0038: leave.s IL_0049 } finally { IL_003a: ldloca.s V_2 IL_003c: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_0042: callvirt ""void System.IDisposable.Dispose()"" IL_0047: nop IL_0048: endfinally } IL_0049: nop IL_004a: ldloc.0 IL_004b: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0050: brtrue.s IL_000f IL_0052: leave.s IL_0069 } finally { IL_0054: ldloc.0 IL_0055: isinst ""System.IDisposable"" IL_005a: stloc.s V_11 IL_005c: ldloc.s V_11 IL_005e: brfalse.s IL_0068 IL_0060: ldloc.s V_11 IL_0062: callvirt ""void System.IDisposable.Dispose()"" IL_0067: nop IL_0068: endfinally } IL_0069: nop IL_006a: call ""System.Collections.Generic.List<object> C.F4()"" IL_006f: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_0074: stloc.s V_5 .try { IL_0076: br.s IL_00f2 IL_0078: ldloca.s V_5 IL_007a: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_007f: stloc.s V_6 IL_0081: nop IL_0082: nop IL_0083: call ""System.Collections.IEnumerable C.F3()"" IL_0088: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_008d: stloc.s V_7 .try { IL_008f: br.s IL_009c IL_0091: ldloc.s V_7 IL_0093: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0098: stloc.s V_8 IL_009a: nop IL_009b: nop IL_009c: ldloc.s V_7 IL_009e: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_00a3: brtrue.s IL_0091 IL_00a5: leave.s IL_00bd } finally { IL_00a7: ldloc.s V_7 IL_00a9: isinst ""System.IDisposable"" IL_00ae: stloc.s V_11 IL_00b0: ldloc.s V_11 IL_00b2: brfalse.s IL_00bc IL_00b4: ldloc.s V_11 IL_00b6: callvirt ""void System.IDisposable.Dispose()"" IL_00bb: nop IL_00bc: endfinally } IL_00bd: nop IL_00be: call ""System.Collections.Generic.List<object> C.F2()"" IL_00c3: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_00c8: stloc.s V_9 .try { IL_00ca: br.s IL_00d7 IL_00cc: ldloca.s V_9 IL_00ce: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_00d3: stloc.s V_10 IL_00d5: nop IL_00d6: nop IL_00d7: ldloca.s V_9 IL_00d9: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_00de: brtrue.s IL_00cc IL_00e0: leave.s IL_00f1 } finally { IL_00e2: ldloca.s V_9 IL_00e4: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_00ea: callvirt ""void System.IDisposable.Dispose()"" IL_00ef: nop IL_00f0: endfinally } IL_00f1: nop IL_00f2: ldloca.s V_5 IL_00f4: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_00f9: brtrue IL_0078 IL_00fe: leave.s IL_010f } finally { IL_0100: ldloca.s V_5 IL_0102: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_0108: callvirt ""void System.IDisposable.Dispose()"" IL_010d: nop IL_010e: endfinally } IL_010f: ret }"); } [Fact] public void ForEachArray1() { var source = @"class C { static void M(double[,,] c) { foreach (var x in c) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 111 (0x6f) .maxstack 4 .locals init (double[,,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, int V_6, double V_7) //x -IL_0000: nop -IL_0001: nop -IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldc.i4.0 IL_0006: callvirt ""int System.Array.GetUpperBound(int)"" IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: callvirt ""int System.Array.GetUpperBound(int)"" IL_0013: stloc.2 IL_0014: ldloc.0 IL_0015: ldc.i4.2 IL_0016: callvirt ""int System.Array.GetUpperBound(int)"" IL_001b: stloc.3 IL_001c: ldloc.0 IL_001d: ldc.i4.0 IL_001e: callvirt ""int System.Array.GetLowerBound(int)"" IL_0023: stloc.s V_4 ~IL_0025: br.s IL_0069 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: callvirt ""int System.Array.GetLowerBound(int)"" IL_002e: stloc.s V_5 ~IL_0030: br.s IL_005e IL_0032: ldloc.0 IL_0033: ldc.i4.2 IL_0034: callvirt ""int System.Array.GetLowerBound(int)"" IL_0039: stloc.s V_6 ~IL_003b: br.s IL_0053 -IL_003d: ldloc.0 IL_003e: ldloc.s V_4 IL_0040: ldloc.s V_5 IL_0042: ldloc.s V_6 IL_0044: call ""double[*,*,*].Get"" IL_0049: stloc.s V_7 -IL_004b: nop -IL_004c: nop ~IL_004d: ldloc.s V_6 IL_004f: ldc.i4.1 IL_0050: add IL_0051: stloc.s V_6 -IL_0053: ldloc.s V_6 IL_0055: ldloc.3 IL_0056: ble.s IL_003d ~IL_0058: ldloc.s V_5 IL_005a: ldc.i4.1 IL_005b: add IL_005c: stloc.s V_5 -IL_005e: ldloc.s V_5 IL_0060: ldloc.2 IL_0061: ble.s IL_0032 ~IL_0063: ldloc.s V_4 IL_0065: ldc.i4.1 IL_0066: add IL_0067: stloc.s V_4 -IL_0069: ldloc.s V_4 IL_006b: ldloc.1 IL_006c: ble.s IL_0027 -IL_006e: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 111 (0x6f) .maxstack 4 .locals init (double[,,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, int V_6, double V_7) //x -IL_0000: nop -IL_0001: nop -IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldc.i4.0 IL_0006: callvirt ""int System.Array.GetUpperBound(int)"" IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: callvirt ""int System.Array.GetUpperBound(int)"" IL_0013: stloc.2 IL_0014: ldloc.0 IL_0015: ldc.i4.2 IL_0016: callvirt ""int System.Array.GetUpperBound(int)"" IL_001b: stloc.3 IL_001c: ldloc.0 IL_001d: ldc.i4.0 IL_001e: callvirt ""int System.Array.GetLowerBound(int)"" IL_0023: stloc.s V_4 ~IL_0025: br.s IL_0069 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: callvirt ""int System.Array.GetLowerBound(int)"" IL_002e: stloc.s V_5 ~IL_0030: br.s IL_005e IL_0032: ldloc.0 IL_0033: ldc.i4.2 IL_0034: callvirt ""int System.Array.GetLowerBound(int)"" IL_0039: stloc.s V_6 ~IL_003b: br.s IL_0053 -IL_003d: ldloc.0 IL_003e: ldloc.s V_4 IL_0040: ldloc.s V_5 IL_0042: ldloc.s V_6 IL_0044: call ""double[*,*,*].Get"" IL_0049: stloc.s V_7 -IL_004b: nop -IL_004c: nop ~IL_004d: ldloc.s V_6 IL_004f: ldc.i4.1 IL_0050: add IL_0051: stloc.s V_6 -IL_0053: ldloc.s V_6 IL_0055: ldloc.3 IL_0056: ble.s IL_003d ~IL_0058: ldloc.s V_5 IL_005a: ldc.i4.1 IL_005b: add IL_005c: stloc.s V_5 -IL_005e: ldloc.s V_5 IL_0060: ldloc.2 IL_0061: ble.s IL_0032 ~IL_0063: ldloc.s V_4 IL_0065: ldc.i4.1 IL_0066: add IL_0067: stloc.s V_4 -IL_0069: ldloc.s V_4 IL_006b: ldloc.1 IL_006c: ble.s IL_0027 -IL_006e: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ForEachArray2() { var source = @"class C { static void M(string a, object[] b, double[,,] c) { foreach (var x in a) { foreach (var y in b) { } } foreach (var x in c) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 184 (0xb8) .maxstack 4 .locals init (string V_0, int V_1, char V_2, //x object[] V_3, int V_4, object V_5, //y double[,,] V_6, int V_7, int V_8, int V_9, int V_10, int V_11, int V_12, double V_13) //x IL_0000: nop IL_0001: nop IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldc.i4.0 IL_0005: stloc.1 IL_0006: br.s IL_0033 IL_0008: ldloc.0 IL_0009: ldloc.1 IL_000a: callvirt ""char string.this[int].get"" IL_000f: stloc.2 IL_0010: nop IL_0011: nop IL_0012: ldarg.1 IL_0013: stloc.3 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0027 IL_0019: ldloc.3 IL_001a: ldloc.s V_4 IL_001c: ldelem.ref IL_001d: stloc.s V_5 IL_001f: nop IL_0020: nop IL_0021: ldloc.s V_4 IL_0023: ldc.i4.1 IL_0024: add IL_0025: stloc.s V_4 IL_0027: ldloc.s V_4 IL_0029: ldloc.3 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0019 IL_002e: nop IL_002f: ldloc.1 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.1 IL_0033: ldloc.1 IL_0034: ldloc.0 IL_0035: callvirt ""int string.Length.get"" IL_003a: blt.s IL_0008 IL_003c: nop IL_003d: ldarg.2 IL_003e: stloc.s V_6 IL_0040: ldloc.s V_6 IL_0042: ldc.i4.0 IL_0043: callvirt ""int System.Array.GetUpperBound(int)"" IL_0048: stloc.s V_7 IL_004a: ldloc.s V_6 IL_004c: ldc.i4.1 IL_004d: callvirt ""int System.Array.GetUpperBound(int)"" IL_0052: stloc.s V_8 IL_0054: ldloc.s V_6 IL_0056: ldc.i4.2 IL_0057: callvirt ""int System.Array.GetUpperBound(int)"" IL_005c: stloc.s V_9 IL_005e: ldloc.s V_6 IL_0060: ldc.i4.0 IL_0061: callvirt ""int System.Array.GetLowerBound(int)"" IL_0066: stloc.s V_10 IL_0068: br.s IL_00b1 IL_006a: ldloc.s V_6 IL_006c: ldc.i4.1 IL_006d: callvirt ""int System.Array.GetLowerBound(int)"" IL_0072: stloc.s V_11 IL_0074: br.s IL_00a5 IL_0076: ldloc.s V_6 IL_0078: ldc.i4.2 IL_0079: callvirt ""int System.Array.GetLowerBound(int)"" IL_007e: stloc.s V_12 IL_0080: br.s IL_0099 IL_0082: ldloc.s V_6 IL_0084: ldloc.s V_10 IL_0086: ldloc.s V_11 IL_0088: ldloc.s V_12 IL_008a: call ""double[*,*,*].Get"" IL_008f: stloc.s V_13 IL_0091: nop IL_0092: nop IL_0093: ldloc.s V_12 IL_0095: ldc.i4.1 IL_0096: add IL_0097: stloc.s V_12 IL_0099: ldloc.s V_12 IL_009b: ldloc.s V_9 IL_009d: ble.s IL_0082 IL_009f: ldloc.s V_11 IL_00a1: ldc.i4.1 IL_00a2: add IL_00a3: stloc.s V_11 IL_00a5: ldloc.s V_11 IL_00a7: ldloc.s V_8 IL_00a9: ble.s IL_0076 IL_00ab: ldloc.s V_10 IL_00ad: ldc.i4.1 IL_00ae: add IL_00af: stloc.s V_10 IL_00b1: ldloc.s V_10 IL_00b3: ldloc.s V_7 IL_00b5: ble.s IL_006a IL_00b7: ret }"); } /// <summary> /// Unlike Dev12 we can handle array with more than 256 dimensions. /// </summary> [Fact] public void ForEachArray_ToManyDimensions() { var source = @"class C { static void M(object o) { foreach (var x in (object[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,])o) { } } }"; // Make sure the source contains an array with too many dimensions. var tooManyCommas = new string(',', 256); Assert.True(source.IndexOf(tooManyCommas, StringComparison.Ordinal) > 0); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); } [Fact] public void ForEachWithDynamicAndTuple() { var source = @"class C { static void M((dynamic, int) t) { foreach (var o in t.Item1) { } } }"; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 119 (0x77) .maxstack 3 .locals init (System.Collections.IEnumerator V_0, object V_1, //o [unchanged] V_2, System.IDisposable V_3) IL_0000: nop IL_0001: nop IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_0007: brfalse.s IL_000b IL_0009: br.s IL_002f IL_000b: ldc.i4.0 IL_000c: ldtoken ""System.Collections.IEnumerable"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldtoken ""C"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0025: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_002f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_0034: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>>.Target"" IL_0039: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_003e: ldarg.0 IL_003f: ldfld ""dynamic System.ValueTuple<dynamic, int>.Item1"" IL_0044: callvirt ""System.Collections.IEnumerable System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0049: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_004e: stloc.0 .try { IL_004f: br.s IL_005a IL_0051: ldloc.0 IL_0052: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0057: stloc.1 IL_0058: nop IL_0059: nop IL_005a: ldloc.0 IL_005b: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0060: brtrue.s IL_0051 IL_0062: leave.s IL_0076 } finally { IL_0064: ldloc.0 IL_0065: isinst ""System.IDisposable"" IL_006a: stloc.3 IL_006b: ldloc.3 IL_006c: brfalse.s IL_0075 IL_006e: ldloc.3 IL_006f: callvirt ""void System.IDisposable.Dispose()"" IL_0074: nop IL_0075: endfinally } IL_0076: ret }"); } [Fact] public void RemoveRestoreNullableAtArrayElement() { var source0 = MarkedSource( @"using System; class C { public static void M() { var <N:1>arr</N:1> = new string?[] { ""0"" }; <N:0>foreach</N:0> (var s in arr) { Console.WriteLine(1); } } }"); // Remove nullable var source1 = MarkedSource( @"using System; class C { public static void M() { var <N:1>arr</N:1> = new string[] { ""0"" }; <N:0>foreach</N:0> (var s in arr) { Console.WriteLine(1); } } }"); // Restore nullable var source2 = source0; var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: nop IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_0028 IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 IL_001b: nop IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: nop IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 IL_002e: ret }"); var compilation1 = CreateCompilation(source1.Tree, options: TestOptions.DebugDll); var compilation2 = compilation0.WithSource(source2.Tree); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: nop IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_0028 IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 IL_001b: nop IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: nop IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 IL_002e: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 -IL_0010: nop -IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 ~IL_0015: br.s IL_0028 -IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 -IL_001b: nop -IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop -IL_0023: nop ~IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 -IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 -IL_002e: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void AddAndDelete() { var source0 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { lock (F1()) { } foreach (var c in F2()) { } using (F3()) { } } }"; // Delete one statement. var source1 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { lock (F1()) { } foreach (var c in F2()) { } } }"; // Add statement with same temp kind. var source2 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { using (F3()) { } lock (F1()) { } foreach (var c in F2()) { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 93 (0x5d) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c System.IDisposable V_5) IL_0000: nop IL_0001: call ""object C.F1()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: nop IL_0022: call ""string C.F2()"" IL_0027: stloc.2 IL_0028: ldc.i4.0 IL_0029: stloc.3 IL_002a: br.s IL_003b IL_002c: ldloc.2 IL_002d: ldloc.3 IL_002e: callvirt ""char string.this[int].get"" IL_0033: stloc.s V_4 IL_0035: nop IL_0036: nop IL_0037: ldloc.3 IL_0038: ldc.i4.1 IL_0039: add IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldloc.2 IL_003d: callvirt ""int string.Length.get"" IL_0042: blt.s IL_002c IL_0044: call ""System.IDisposable C.F3()"" IL_0049: stloc.s V_5 .try { IL_004b: nop IL_004c: nop IL_004d: leave.s IL_005c } finally { IL_004f: ldloc.s V_5 IL_0051: brfalse.s IL_005b IL_0053: ldloc.s V_5 IL_0055: callvirt ""void System.IDisposable.Dispose()"" IL_005a: nop IL_005b: endfinally } IL_005c: ret }"); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var compilation2 = compilation0.WithSource(source2); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 69 (0x45) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c [unchanged] V_5) IL_0000: nop IL_0001: call ""object C.F1()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: nop IL_0022: call ""string C.F2()"" IL_0027: stloc.2 IL_0028: ldc.i4.0 IL_0029: stloc.3 IL_002a: br.s IL_003b IL_002c: ldloc.2 IL_002d: ldloc.3 IL_002e: callvirt ""char string.this[int].get"" IL_0033: stloc.s V_4 IL_0035: nop IL_0036: nop IL_0037: ldloc.3 IL_0038: ldc.i4.1 IL_0039: add IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldloc.2 IL_003d: callvirt ""int string.Length.get"" IL_0042: blt.s IL_002c IL_0044: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 93 (0x5d) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c [unchanged] V_5, System.IDisposable V_6) -IL_0000: nop -IL_0001: call ""System.IDisposable C.F3()"" IL_0006: stloc.s V_6 .try { -IL_0008: nop -IL_0009: nop IL_000a: leave.s IL_0019 } finally { ~IL_000c: ldloc.s V_6 IL_000e: brfalse.s IL_0018 IL_0010: ldloc.s V_6 IL_0012: callvirt ""void System.IDisposable.Dispose()"" IL_0017: nop ~IL_0018: endfinally } -IL_0019: call ""object C.F1()"" IL_001e: stloc.0 IL_001f: ldc.i4.0 IL_0020: stloc.1 .try { IL_0021: ldloc.0 IL_0022: ldloca.s V_1 IL_0024: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0029: nop -IL_002a: nop -IL_002b: nop IL_002c: leave.s IL_0039 } finally { ~IL_002e: ldloc.1 IL_002f: brfalse.s IL_0038 IL_0031: ldloc.0 IL_0032: call ""void System.Threading.Monitor.Exit(object)"" IL_0037: nop ~IL_0038: endfinally } -IL_0039: nop -IL_003a: call ""string C.F2()"" IL_003f: stloc.2 IL_0040: ldc.i4.0 IL_0041: stloc.3 ~IL_0042: br.s IL_0053 -IL_0044: ldloc.2 IL_0045: ldloc.3 IL_0046: callvirt ""char string.this[int].get"" IL_004b: stloc.s V_4 -IL_004d: nop -IL_004e: nop ~IL_004f: ldloc.3 IL_0050: ldc.i4.1 IL_0051: add IL_0052: stloc.3 -IL_0053: ldloc.3 IL_0054: ldloc.2 IL_0055: callvirt ""int string.Length.get"" IL_005a: blt.s IL_0044 -IL_005c: ret }", methodToken: diff2.EmitResult.UpdatedMethods.Single()); } [Fact] public void Insert() { var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } static void M() { lock (F1()) { } lock (F2()) { } } }"; var source1 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } static void M() { lock (F3()) { } // added lock (F1()) { } lock (F4()) { } // replaced } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Note that the order of unique ids in temporaries follows the // order of declaration in the updated method. Specifically, the // original temporary names (and unique ids) are not preserved. // (Should not be an issue since the names are used by EnC only.) diff1.VerifyIL("C.M", @"{ // Code size 108 (0x6c) .maxstack 2 .locals init (object V_0, bool V_1, [object] V_2, [bool] V_3, object V_4, bool V_5, object V_6, bool V_7) IL_0000: nop IL_0001: call ""object C.F3()"" IL_0006: stloc.s V_4 IL_0008: ldc.i4.0 IL_0009: stloc.s V_5 .try { IL_000b: ldloc.s V_4 IL_000d: ldloca.s V_5 IL_000f: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0014: nop IL_0015: nop IL_0016: nop IL_0017: leave.s IL_0026 } finally { IL_0019: ldloc.s V_5 IL_001b: brfalse.s IL_0025 IL_001d: ldloc.s V_4 IL_001f: call ""void System.Threading.Monitor.Exit(object)"" IL_0024: nop IL_0025: endfinally } IL_0026: call ""object C.F1()"" IL_002b: stloc.0 IL_002c: ldc.i4.0 IL_002d: stloc.1 .try { IL_002e: ldloc.0 IL_002f: ldloca.s V_1 IL_0031: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0036: nop IL_0037: nop IL_0038: nop IL_0039: leave.s IL_0046 } finally { IL_003b: ldloc.1 IL_003c: brfalse.s IL_0045 IL_003e: ldloc.0 IL_003f: call ""void System.Threading.Monitor.Exit(object)"" IL_0044: nop IL_0045: endfinally } IL_0046: call ""object C.F4()"" IL_004b: stloc.s V_6 IL_004d: ldc.i4.0 IL_004e: stloc.s V_7 .try { IL_0050: ldloc.s V_6 IL_0052: ldloca.s V_7 IL_0054: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0059: nop IL_005a: nop IL_005b: nop IL_005c: leave.s IL_006b } finally { IL_005e: ldloc.s V_7 IL_0060: brfalse.s IL_006a IL_0062: ldloc.s V_6 IL_0064: call ""void System.Threading.Monitor.Exit(object)"" IL_0069: nop IL_006a: endfinally } IL_006b: ret }"); } /// <summary> /// Should not reuse temporary locals /// having different temporary kinds. /// </summary> [Fact] public void NoReuseDifferentTempKind() { var source = @"class A : System.IDisposable { public object Current { get { return null; } } public bool MoveNext() { return false; } public void Dispose() { } internal int this[A a] { get { return 0; } set { } } } class B { public A GetEnumerator() { return null; } } class C { static A F() { return null; } static B G() { return null; } static void M(A a) { a[F()]++; using (F()) { } lock (F()) { } foreach (var o in G()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 137 (0x89) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, A V_2, A V_3, bool V_4, A V_5, object V_6, //o A V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""A C.F()"" IL_0007: stloc.s V_7 IL_0009: dup IL_000a: ldloc.s V_7 IL_000c: callvirt ""int A.this[A].get"" IL_0011: stloc.s V_8 IL_0013: ldloc.s V_7 IL_0015: ldloc.s V_8 IL_0017: ldc.i4.1 IL_0018: add IL_0019: callvirt ""void A.this[A].set"" IL_001e: nop IL_001f: call ""A C.F()"" IL_0024: stloc.2 .try { IL_0025: nop IL_0026: nop IL_0027: leave.s IL_0034 } finally { IL_0029: ldloc.2 IL_002a: brfalse.s IL_0033 IL_002c: ldloc.2 IL_002d: callvirt ""void System.IDisposable.Dispose()"" IL_0032: nop IL_0033: endfinally } IL_0034: call ""A C.F()"" IL_0039: stloc.3 IL_003a: ldc.i4.0 IL_003b: stloc.s V_4 .try { IL_003d: ldloc.3 IL_003e: ldloca.s V_4 IL_0040: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0045: nop IL_0046: nop IL_0047: nop IL_0048: leave.s IL_0056 } finally { IL_004a: ldloc.s V_4 IL_004c: brfalse.s IL_0055 IL_004e: ldloc.3 IL_004f: call ""void System.Threading.Monitor.Exit(object)"" IL_0054: nop IL_0055: endfinally } IL_0056: nop IL_0057: call ""B C.G()"" IL_005c: callvirt ""A B.GetEnumerator()"" IL_0061: stloc.s V_5 .try { IL_0063: br.s IL_0070 IL_0065: ldloc.s V_5 IL_0067: callvirt ""object A.Current.get"" IL_006c: stloc.s V_6 IL_006e: nop IL_006f: nop IL_0070: ldloc.s V_5 IL_0072: callvirt ""bool A.MoveNext()"" IL_0077: brtrue.s IL_0065 IL_0079: leave.s IL_0088 } finally { IL_007b: ldloc.s V_5 IL_007d: brfalse.s IL_0087 IL_007f: ldloc.s V_5 IL_0081: callvirt ""void System.IDisposable.Dispose()"" IL_0086: nop IL_0087: endfinally } IL_0088: ret }"); } [Fact] public void Switch_String() { var source0 = @"class C { static string F() { return null; } static void M() { switch (F()) { case ""a"": System.Console.WriteLine(1); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var source1 = @"class C { static string F() { return null; } static void M() { switch (F()) { case ""a"": System.Console.WriteLine(10); break; case ""b"": System.Console.WriteLine(20); break; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); // Validate presence of a hidden sequence point @IL_0007 that is required for proper function remapping. v0.VerifyIL("C.M", @" { // Code size 56 (0x38) .maxstack 2 .locals init (string V_0, string V_1) -IL_0000: nop -IL_0001: call ""string C.F()"" IL_0006: stloc.1 ~IL_0007: ldloc.1 IL_0008: stloc.0 ~IL_0009: ldloc.0 IL_000a: ldstr ""a"" IL_000f: call ""bool string.op_Equality(string, string)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldstr ""b"" IL_001c: call ""bool string.op_Equality(string, string)"" IL_0021: brtrue.s IL_002e IL_0023: br.s IL_0037 -IL_0025: ldc.i4.1 IL_0026: call ""void System.Console.WriteLine(int)"" IL_002b: nop -IL_002c: br.s IL_0037 -IL_002e: ldc.i4.2 IL_002f: call ""void System.Console.WriteLine(int)"" IL_0034: nop -IL_0035: br.s IL_0037 -IL_0037: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.SwitchStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 58 (0x3a) .maxstack 2 .locals init (string V_0, string V_1) -IL_0000: nop -IL_0001: call ""string C.F()"" IL_0006: stloc.1 ~IL_0007: ldloc.1 IL_0008: stloc.0 ~IL_0009: ldloc.0 IL_000a: ldstr ""a"" IL_000f: call ""bool string.op_Equality(string, string)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldstr ""b"" IL_001c: call ""bool string.op_Equality(string, string)"" IL_0021: brtrue.s IL_002f IL_0023: br.s IL_0039 -IL_0025: ldc.i4.s 10 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop -IL_002d: br.s IL_0039 -IL_002f: ldc.i4.s 20 IL_0031: call ""void System.Console.WriteLine(int)"" IL_0036: nop -IL_0037: br.s IL_0039 -IL_0039: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Switch_Integer() { var source0 = WithWindowsLineBreaks( @"class C { static int F() { return 1; } static void M() { switch (F()) { case 1: System.Console.WriteLine(1); break; case 2: System.Console.WriteLine(2); break; } } }"); var source1 = WithWindowsLineBreaks( @"class C { static int F() { return 1; } static void M() { switch (F()) { case 1: System.Console.WriteLine(10); break; case 2: System.Console.WriteLine(20); break; } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 40 (0x28) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: call ""int C.F()"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: ldc.i4.1 IL_000b: beq.s IL_0015 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ldc.i4.2 IL_0011: beq.s IL_001e IL_0013: br.s IL_0027 IL_0015: ldc.i4.1 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: br.s IL_0027 IL_001e: ldc.i4.2 IL_001f: call ""void System.Console.WriteLine(int)"" IL_0024: nop IL_0025: br.s IL_0027 IL_0027: ret }"); // Validate that we emit a hidden sequence point @IL_0007. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""21"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x9"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""49"" document=""1"" /> <entry offset=""0x1c"" startLine=""9"" startColumn=""50"" endLine=""9"" endColumn=""56"" document=""1"" /> <entry offset=""0x1e"" startLine=""10"" startColumn=""21"" endLine=""10"" endColumn=""49"" document=""1"" /> <entry offset=""0x25"" startLine=""10"" startColumn=""50"" endLine=""10"" endColumn=""56"" document=""1"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.SwitchStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: call ""int C.F()"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: ldc.i4.1 IL_000b: beq.s IL_0015 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ldc.i4.2 IL_0011: beq.s IL_001f IL_0013: br.s IL_0029 IL_0015: ldc.i4.s 10 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: br.s IL_0029 IL_001f: ldc.i4.s 20 IL_0021: call ""void System.Console.WriteLine(int)"" IL_0026: nop IL_0027: br.s IL_0029 IL_0029: ret }"); } [Fact] public void Switch_Patterns() { var source = WithWindowsLineBreaks(@" using static System.Console; class C { static object F() => 1; static bool P() => false; static void M() { switch (F()) { case 1: WriteLine(""int 1""); break; case byte b when P(): WriteLine(b); break; case int i when P(): WriteLine(i); break; case (byte)1: WriteLine(""byte 1""); break; case int j: WriteLine(j); break; case object o: WriteLine(o); break; } } }"); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""0"" offset=""106"" /> <slot kind=""0"" offset=""162"" /> <slot kind=""0"" offset=""273"" /> <slot kind=""0"" offset=""323"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>", options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints); v0.VerifyIL("C.M", @" { // Code size 147 (0x93) .maxstack 2 .locals init (byte V_0, //b int V_1, //i int V_2, //j object V_3, //o object V_4) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.s V_4 IL_0008: ldloc.s V_4 IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: isinst ""int"" IL_0011: brfalse.s IL_0020 IL_0013: ldloc.3 IL_0014: unbox.any ""int"" IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: beq.s IL_003c IL_001e: br.s IL_005b IL_0020: ldloc.3 IL_0021: isinst ""byte"" IL_0026: brfalse.s IL_0037 IL_0028: ldloc.3 IL_0029: unbox.any ""byte"" IL_002e: stloc.0 IL_002f: br.s IL_0049 IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: beq.s IL_006d IL_0035: br.s IL_0087 IL_0037: ldloc.3 IL_0038: brtrue.s IL_0087 IL_003a: br.s IL_0092 IL_003c: ldstr ""int 1"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: nop IL_0047: br.s IL_0092 IL_0049: call ""bool C.P()"" IL_004e: brtrue.s IL_0052 IL_0050: br.s IL_0031 IL_0052: ldloc.0 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: br.s IL_0092 IL_005b: call ""bool C.P()"" IL_0060: brtrue.s IL_0064 IL_0062: br.s IL_007a IL_0064: ldloc.1 IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: nop IL_006b: br.s IL_0092 IL_006d: ldstr ""byte 1"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: nop IL_0078: br.s IL_0092 IL_007a: ldloc.1 IL_007b: stloc.2 IL_007c: br.s IL_007e IL_007e: ldloc.2 IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: nop IL_0085: br.s IL_0092 IL_0087: br.s IL_0089 IL_0089: ldloc.3 IL_008a: call ""void System.Console.WriteLine(object)"" IL_008f: nop IL_0090: br.s IL_0092 IL_0092: ret }"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 147 (0x93) .maxstack 2 .locals init (byte V_0, //b int V_1, //i int V_2, //j object V_3, //o object V_4) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.s V_4 IL_0008: ldloc.s V_4 IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: isinst ""int"" IL_0011: brfalse.s IL_0020 IL_0013: ldloc.3 IL_0014: unbox.any ""int"" IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: beq.s IL_003c IL_001e: br.s IL_005b IL_0020: ldloc.3 IL_0021: isinst ""byte"" IL_0026: brfalse.s IL_0037 IL_0028: ldloc.3 IL_0029: unbox.any ""byte"" IL_002e: stloc.0 IL_002f: br.s IL_0049 IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: beq.s IL_006d IL_0035: br.s IL_0087 IL_0037: ldloc.3 IL_0038: brtrue.s IL_0087 IL_003a: br.s IL_0092 IL_003c: ldstr ""int 1"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: nop IL_0047: br.s IL_0092 IL_0049: call ""bool C.P()"" IL_004e: brtrue.s IL_0052 IL_0050: br.s IL_0031 IL_0052: ldloc.0 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: br.s IL_0092 IL_005b: call ""bool C.P()"" IL_0060: brtrue.s IL_0064 IL_0062: br.s IL_007a IL_0064: ldloc.1 IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: nop IL_006b: br.s IL_0092 IL_006d: ldstr ""byte 1"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: nop IL_0078: br.s IL_0092 IL_007a: ldloc.1 IL_007b: stloc.2 IL_007c: br.s IL_007e IL_007e: ldloc.2 IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: nop IL_0085: br.s IL_0092 IL_0087: br.s IL_0089 IL_0089: ldloc.3 IL_008a: call ""void System.Console.WriteLine(object)"" IL_008f: nop IL_0090: br.s IL_0092 IL_0092: ret }"); } [Fact] public void If() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { if (F()) { System.Console.WriteLine(1); } } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { if (F()) { System.Console.WriteLine(10); } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: call ""bool C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0013 IL_000a: nop IL_000b: ldc.i4.1 IL_000c: call ""void System.Console.WriteLine(int)"" IL_0011: nop IL_0012: nop IL_0013: ret } "); // Validate presence of a hidden sequence point @IL_0007 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x12"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x13"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.IfStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 21 (0x15) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: call ""bool C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0014 IL_000a: nop IL_000b: ldc.i4.s 10 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: nop IL_0014: ret }"); } [Fact] public void While() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { while (F()) { System.Console.WriteLine(1); } } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { while (F()) { System.Console.WriteLine(10); } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: br.s IL_000c IL_0003: nop IL_0004: ldc.i4.1 IL_0005: call ""void System.Console.WriteLine(int)"" IL_000a: nop IL_000b: nop IL_000c: call ""bool C.F()"" IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: brtrue.s IL_0003 IL_0015: ret } "); // Validate presence of a hidden sequence point @IL_0012 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0xb"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xc"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""20"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.WhileStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: br.s IL_000d IL_0003: nop IL_0004: ldc.i4.s 10 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: nop IL_000d: call ""bool C.F()"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: brtrue.s IL_0003 IL_0016: ret }"); } [Fact] public void Do1() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { do { System.Console.WriteLine(1); } while (F()); } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { do { System.Console.WriteLine(10); } while (F()); } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: nop IL_0002: ldc.i4.1 IL_0003: call ""void System.Console.WriteLine(int)"" IL_0008: nop IL_0009: nop IL_000a: call ""bool C.F()"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: brtrue.s IL_0001 IL_0013: ret }"); // Validate presence of a hidden sequence point @IL_0010 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x9"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""21"" document=""1"" /> <entry offset=""0x10"" hidden=""true"" document=""1"" /> <entry offset=""0x13"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.DoStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 21 (0x15) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: nop IL_0002: ldc.i4.s 10 IL_0004: call ""void System.Console.WriteLine(int)"" IL_0009: nop IL_000a: nop IL_000b: call ""bool C.F()"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: brtrue.s IL_0001 IL_0014: ret }"); } [Fact] public void For() { var source0 = @" class C { static bool F(int i) { return true; } static void G(int i) { } static void M() { for (int i = 1; F(i); G(i)) { System.Console.WriteLine(1); } } }"; var source1 = @" class C { static bool F(int i) { return true; } static void G(int i) { } static void M() { for (int i = 1; F(i); G(i)) { System.Console.WriteLine(10); } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); // Validate presence of a hidden sequence point @IL_001c that is required for proper function remapping. v0.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 1 .locals init (int V_0, //i bool V_1) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 ~IL_0003: br.s IL_0015 -IL_0005: nop -IL_0006: ldc.i4.1 IL_0007: call ""void System.Console.WriteLine(int)"" IL_000c: nop -IL_000d: nop -IL_000e: ldloc.0 IL_000f: call ""void C.G(int)"" IL_0014: nop -IL_0015: ldloc.0 IL_0016: call ""bool C.F(int)"" IL_001b: stloc.1 ~IL_001c: ldloc.1 IL_001d: brtrue.s IL_0005 -IL_001f: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.ForStatement, SyntaxKind.VariableDeclarator), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, //i bool V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: br.s IL_0016 IL_0005: nop IL_0006: ldc.i4.s 10 IL_0008: call ""void System.Console.WriteLine(int)"" IL_000d: nop IL_000e: nop IL_000f: ldloc.0 IL_0010: call ""void C.G(int)"" IL_0015: nop IL_0016: ldloc.0 IL_0017: call ""bool C.F(int)"" IL_001c: stloc.1 IL_001d: ldloc.1 IL_001e: brtrue.s IL_0005 IL_0020: ret } "); } [Fact] public void SynthesizedVariablesInLambdas1() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { var f = new System.Action(() => { lock (F()) { } }); } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<>c.<M>b__1_0()", @" { // Code size 34 (0x22) .maxstack 2 .locals init (object V_0, bool V_1) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: ret }"); #if TODO // identify the lambda in a semantic edit var methodData0 = v0.TestData.GetMethodData("C.<M>b__0"); var method0 = compilation0.GetMember<MethodSymbol>("C.<M>b__0"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("C.<M>b__0"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.<M>b__0", @" ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void SynthesizedVariablesInLambdas2() { var source0 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(1); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var source1 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(10); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var source2 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(100); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <M>b__0_0, <M>b__0_1}"); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <M>b__0_0, <M>b__0_1}"); var expectedIL = @" { // Code size 33 (0x21) .maxstack 2 .locals init (int[] V_0, int V_1, int V_2) //x IL_0000: nop IL_0001: nop IL_0002: ldarg.1 IL_0003: stloc.0 IL_0004: ldc.i4.0 IL_0005: stloc.1 IL_0006: br.s IL_001a IL_0008: ldloc.0 IL_0009: ldloc.1 IL_000a: ldelem.i4 IL_000b: stloc.2 IL_000c: nop IL_000d: ldc.i4.s 20 IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: nop IL_0016: ldloc.1 IL_0017: ldc.i4.1 IL_0018: add IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldloc.0 IL_001c: ldlen IL_001d: conv.i4 IL_001e: blt.s IL_0008 IL_0020: ret }"; diff1.VerifyIL(@"C.<>c.<M>b__0_1", expectedIL); diff2.VerifyIL(@"C.<>c.<M>b__0_1", expectedIL); } [Fact] public void SynthesizedVariablesInIterator1() { var source = @" using System.Collections.Generic; class C { public IEnumerable<int> F() { lock (F()) { } yield return 1; } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 131 (0x83) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_007a IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldarg.0 IL_0022: ldfld ""C C.<F>d__0.<>4__this"" IL_0027: call ""System.Collections.Generic.IEnumerable<int> C.F()"" IL_002c: stfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_0031: ldarg.0 IL_0032: ldc.i4.0 IL_0033: stfld ""bool C.<F>d__0.<>s__2"" .try { IL_0038: ldarg.0 IL_0039: ldfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_003e: ldarg.0 IL_003f: ldflda ""bool C.<F>d__0.<>s__2"" IL_0044: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0049: nop IL_004a: nop IL_004b: nop IL_004c: leave.s IL_0063 } finally { IL_004e: ldarg.0 IL_004f: ldfld ""bool C.<F>d__0.<>s__2"" IL_0054: brfalse.s IL_0062 IL_0056: ldarg.0 IL_0057: ldfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_005c: call ""void System.Threading.Monitor.Exit(object)"" IL_0061: nop IL_0062: endfinally } IL_0063: ldarg.0 IL_0064: ldnull IL_0065: stfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_006a: ldarg.0 IL_006b: ldc.i4.1 IL_006c: stfld ""int C.<F>d__0.<>2__current"" IL_0071: ldarg.0 IL_0072: ldc.i4.1 IL_0073: stfld ""int C.<F>d__0.<>1__state"" IL_0078: ldc.i4.1 IL_0079: ret IL_007a: ldarg.0 IL_007b: ldc.i4.m1 IL_007c: stfld ""int C.<F>d__0.<>1__state"" IL_0081: ldc.i4.0 IL_0082: ret }"); #if TODO var methodData0 = v0.TestData.GetMethodData("?"); var method0 = compilation0.GetMember<MethodSymbol>("?"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("?"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("?", @" {", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void SynthesizedVariablesInAsyncMethod1() { var source = @" using System.Threading.Tasks; class C { public async Task<int> F() { lock (F()) { } await F(); return 1; } } "; var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 246 (0xf6) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, C.<F>d__0 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_0011 IL_000c: br IL_009e -IL_0011: nop -IL_0012: ldarg.0 IL_0013: ldarg.0 IL_0014: ldfld ""C C.<F>d__0.<>4__this"" IL_0019: call ""System.Threading.Tasks.Task<int> C.F()"" IL_001e: stfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: stfld ""bool C.<F>d__0.<>s__2"" .try { IL_002a: ldarg.0 IL_002b: ldfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0030: ldarg.0 IL_0031: ldflda ""bool C.<F>d__0.<>s__2"" IL_0036: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_003b: nop -IL_003c: nop -IL_003d: nop IL_003e: leave.s IL_0059 } finally { ~IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: bge.s IL_0058 IL_0044: ldarg.0 IL_0045: ldfld ""bool C.<F>d__0.<>s__2"" IL_004a: brfalse.s IL_0058 IL_004c: ldarg.0 IL_004d: ldfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0052: call ""void System.Threading.Monitor.Exit(object)"" IL_0057: nop ~IL_0058: endfinally } ~IL_0059: ldarg.0 IL_005a: ldnull IL_005b: stfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" -IL_0060: ldarg.0 IL_0061: ldfld ""C C.<F>d__0.<>4__this"" IL_0066: call ""System.Threading.Tasks.Task<int> C.F()"" IL_006b: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0070: stloc.2 ~IL_0071: ldloca.s V_2 IL_0073: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0078: brtrue.s IL_00ba IL_007a: ldarg.0 IL_007b: ldc.i4.0 IL_007c: dup IL_007d: stloc.0 IL_007e: stfld ""int C.<F>d__0.<>1__state"" <IL_0083: ldarg.0 IL_0084: ldloc.2 IL_0085: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_008a: ldarg.0 IL_008b: stloc.3 IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0092: ldloca.s V_2 IL_0094: ldloca.s V_3 IL_0096: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)"" IL_009b: nop IL_009c: leave.s IL_00f5 >IL_009e: ldarg.0 IL_009f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_00a4: stloc.2 IL_00a5: ldarg.0 IL_00a6: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_00ab: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00b1: ldarg.0 IL_00b2: ldc.i4.m1 IL_00b3: dup IL_00b4: stloc.0 IL_00b5: stfld ""int C.<F>d__0.<>1__state"" IL_00ba: ldloca.s V_2 IL_00bc: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00c1: pop -IL_00c2: ldc.i4.1 IL_00c3: stloc.1 IL_00c4: leave.s IL_00e0 } catch System.Exception { ~IL_00c6: stloc.s V_4 IL_00c8: ldarg.0 IL_00c9: ldc.i4.s -2 IL_00cb: stfld ""int C.<F>d__0.<>1__state"" IL_00d0: ldarg.0 IL_00d1: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00d6: ldloc.s V_4 IL_00d8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00dd: nop IL_00de: leave.s IL_00f5 } -IL_00e0: ldarg.0 IL_00e1: ldc.i4.s -2 IL_00e3: stfld ""int C.<F>d__0.<>1__state"" ~IL_00e8: ldarg.0 IL_00e9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00ee: ldloc.1 IL_00ef: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00f4: nop IL_00f5: ret }", sequencePoints: "C+<F>d__0.MoveNext"); #if TODO var methodData0 = v0.TestData.GetMethodData("?"); var method0 = compilation0.GetMember<MethodSymbol>("?"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("?"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("?", @" {", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void OutVar() { var source = @" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int x, out var y); return x + y; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop -IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 -IL_0011: ldloc.3 IL_0012: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternVariable() { var source = @" class C { static int F(object o) { if (o is int i) { return i; } return 0; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 ~IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d -IL_0018: nop -IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0021 -IL_001d: ldc.i4.0 IL_001e: stloc.3 IL_001f: br.s IL_0021 -IL_0021: ldloc.3 IL_0022: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Tuple_Parenthesized() { var source = @" class C { static int F() { (int, (int, int)) x = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x [int] V_1, int V_2) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" -IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.2 IL_002f: br.s IL_0031 -IL_0031: ldloc.2 IL_0032: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Tuple_Decomposition() { var source = @" class C { static int F() { (int x, (int y, int z)) = (1, (2, 3)); return x + y + z; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z [int] V_3, int V_4) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 -IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.s V_4 IL_000e: br.s IL_0010 -IL_0010: ldloc.s V_4 IL_0012: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternMatching_Variable() { var source = @" class C { static int F(object o) { if (o is int i) { return i; } return 0; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 ~IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d -IL_0018: nop -IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0021 -IL_001d: ldc.i4.0 IL_001e: stloc.3 IL_001f: br.s IL_0021 -IL_0021: ldloc.3 IL_0022: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternMatching_NoVariable() { var source = @" class C { static int F(object o) { if ((o is bool) || (o is 0)) { return 0; } return 1; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (bool V_0, [int] V_1, int V_2) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brtrue.s IL_001f IL_0009: ldarg.0 IL_000a: isinst ""int"" IL_000f: brfalse.s IL_001c IL_0011: ldarg.0 IL_0012: unbox.any ""int"" IL_0017: ldc.i4.0 IL_0018: ceq IL_001a: br.s IL_001d IL_001c: ldc.i4.0 IL_001d: br.s IL_0020 IL_001f: ldc.i4.1 IL_0020: stloc.0 ~IL_0021: ldloc.0 IL_0022: brfalse.s IL_0029 -IL_0024: nop -IL_0025: ldc.i4.0 IL_0026: stloc.2 IL_0027: br.s IL_002d -IL_0029: ldc.i4.1 IL_002a: stloc.2 IL_002b: br.s IL_002d -IL_002d: ldloc.2 IL_002e: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void VarPattern() { var source = @" using System.Threading.Tasks; class C { static object G(object o1, object o2) { return (o1, o2) switch { (int a, string b) => a, _ => 0 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 62 (0x3e) .maxstack 1 .locals init (int V_0, //a string V_1, //b [int] V_2, [object] V_3, int V_4, object V_5) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 -IL_0004: nop ~IL_0005: ldarg.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0027 IL_000d: ldarg.0 IL_000e: unbox.any ""int"" IL_0013: stloc.0 ~IL_0014: ldarg.1 IL_0015: isinst ""string"" IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: brtrue.s IL_0020 IL_001e: br.s IL_0027 ~IL_0020: br.s IL_0022 -IL_0022: ldloc.0 IL_0023: stloc.s V_4 IL_0025: br.s IL_002c -IL_0027: ldc.i4.0 IL_0028: stloc.s V_4 IL_002a: br.s IL_002c ~IL_002c: ldc.i4.1 IL_002d: brtrue.s IL_0030 -IL_002f: nop ~IL_0030: ldloc.s V_4 IL_0032: box ""int"" IL_0037: stloc.s V_5 IL_0039: br.s IL_003b -IL_003b: ldloc.s V_5 IL_003d: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void RecursiveSwitchExpression() { var source = @" class C { static object G(object o) { return o switch { int i => i switch { 0 => 1, _ => 2, }, _ => 3 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 76 (0x4c) .maxstack 1 .locals init (int V_0, //i [int] V_1, [int] V_2, [object] V_3, int V_4, int V_5, object V_6) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 -IL_0004: nop ~IL_0005: ldarg.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0035 IL_000d: ldarg.0 IL_000e: unbox.any ""int"" IL_0013: stloc.0 ~IL_0014: br.s IL_0016 ~IL_0016: br.s IL_0018 IL_0018: ldc.i4.1 IL_0019: brtrue.s IL_001c -IL_001b: nop ~IL_001c: ldloc.0 IL_001d: brfalse.s IL_0021 IL_001f: br.s IL_0026 -IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b -IL_0026: ldc.i4.2 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b ~IL_002b: ldc.i4.1 IL_002c: brtrue.s IL_002f -IL_002e: nop -IL_002f: ldloc.s V_5 IL_0031: stloc.s V_4 IL_0033: br.s IL_003a -IL_0035: ldc.i4.3 IL_0036: stloc.s V_4 IL_0038: br.s IL_003a ~IL_003a: ldc.i4.1 IL_003b: brtrue.s IL_003e -IL_003d: nop ~IL_003e: ldloc.s V_4 IL_0040: box ""int"" IL_0045: stloc.s V_6 IL_0047: br.s IL_0049 -IL_0049: ldloc.s V_6 IL_004b: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void RecursiveSwitchExpressionWithAwait() { var source = @" using System.Threading.Tasks; class C { static async Task<object> G(object o) { return o switch { Task<int> i when await i > 0 => await i switch { 1 => 1, _ => 2, }, _ => 3 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetEquivalentNodesMap(g1, g0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 56 (0x38) .maxstack 2 .locals init (C.<G>d__0 V_0) ~IL_0000: newobj ""C.<G>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 ~IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""object C.<G>d__0.o"" IL_0018: ldloc.0 -IL_0019: ldc.i4.m1 -IL_001a: stfld ""int C.<G>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<C.<G>d__0>(ref C.<G>d__0)"" IL_002c: ldloc.0 IL_002d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0032: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0037: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void SwitchExpressionInsideAwait() { var source = @" using System.Threading.Tasks; class C { static async Task<object> G(Task<object> o) { return await o switch { int i => 0, _ => 1 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 56 (0x38) .maxstack 2 .locals init (C.<G>d__0 V_0) ~IL_0000: newobj ""C.<G>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 ~IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""System.Threading.Tasks.Task<object> C.<G>d__0.o"" IL_0018: ldloc.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<G>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<C.<G>d__0>(ref C.<G>d__0)"" IL_002c: ldloc.0 <IL_002d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0032: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0037: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void SwitchExpressionWithOutVar() { var source = @" class C { static object G() { return N(out var x) switch { null => x switch {1 => 1, _ => 2 }, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 73 (0x49) .maxstack 2 .locals init (int V_0, //x [int] V_1, [object] V_2, [int] V_3, [object] V_4, int V_5, object V_6, int V_7, object V_8) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: call ""object C.N(out int)"" IL_0008: stloc.s V_6 IL_000a: ldc.i4.1 IL_000b: brtrue.s IL_000e -IL_000d: nop ~IL_000e: ldloc.s V_6 IL_0010: brfalse.s IL_0014 IL_0012: br.s IL_0032 ~IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 -IL_0017: nop ~IL_0018: ldloc.0 IL_0019: ldc.i4.1 IL_001a: beq.s IL_001e IL_001c: br.s IL_0023 -IL_001e: ldc.i4.1 IL_001f: stloc.s V_7 IL_0021: br.s IL_0028 -IL_0023: ldc.i4.2 IL_0024: stloc.s V_7 IL_0026: br.s IL_0028 ~IL_0028: ldc.i4.1 IL_0029: brtrue.s IL_002c -IL_002b: nop -IL_002c: ldloc.s V_7 IL_002e: stloc.s V_5 IL_0030: br.s IL_0037 -IL_0032: ldc.i4.1 IL_0033: stloc.s V_5 IL_0035: br.s IL_0037 ~IL_0037: ldc.i4.1 IL_0038: brtrue.s IL_003b -IL_003a: nop ~IL_003b: ldloc.s V_5 IL_003d: box ""int"" IL_0042: stloc.s V_8 IL_0044: br.s IL_0046 -IL_0046: ldloc.s V_8 IL_0048: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ForEachStatement_Deconstruction() { var source = @" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (x, (y, z)) in F()) { System.Console.WriteLine(x); } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) -IL_0000: nop -IL_0001: nop -IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 ~IL_000c: br.s IL_0045 -IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 -IL_0036: nop -IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop -IL_003e: nop ~IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 -IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e -IL_004d: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ComplexTypes() { var sourceText = @" using System; using System.Collections.Generic; class C1<T> { public enum E { A } } class C { public unsafe static void G() { var <N:0>a</N:0> = new { key = ""a"", value = new List<(int, int)>()}; var <N:1>b</N:1> = (number: 5, value: a); var <N:2>c</N:2> = new[] { b }; int[] <N:3>array</N:3> = { 1, 2, 3 }; ref int <N:4>d</N:4> = ref array[0]; ref readonly int <N:5>e</N:5> = ref array[0]; C1<(int, dynamic)>.E***[,,] <N:6>x</N:6> = null; var <N:7>f</N:7> = new List<string?>(); } } "; var source0 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var source1 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var source2 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithAllowUnsafe(true)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 88 (0x58) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_0035: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldc.i4.0 IL_003d: ldelema ""int"" IL_0042: stloc.s V_4 IL_0044: ldloc.3 IL_0045: ldc.i4.0 IL_0046: ldelema ""int"" IL_004b: stloc.s V_5 IL_004d: ldnull IL_004e: stloc.s V_6 IL_0050: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0055: stloc.s V_7 IL_0057: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 89 (0x59) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldc.i4.0 IL_0031: ldc.i4.1 IL_0032: stelem.i4 IL_0033: dup IL_0034: ldc.i4.1 IL_0035: ldc.i4.2 IL_0036: stelem.i4 IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.3 IL_003a: stelem.i4 IL_003b: stloc.3 IL_003c: ldloc.3 IL_003d: ldc.i4.0 IL_003e: ldelema ""int"" IL_0043: stloc.s V_4 IL_0045: ldloc.3 IL_0046: ldc.i4.0 IL_0047: ldelema ""int"" IL_004c: stloc.s V_5 IL_004e: ldnull IL_004f: stloc.s V_6 IL_0051: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0056: stloc.s V_7 IL_0058: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 89 (0x59) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldc.i4.0 IL_0031: ldc.i4.1 IL_0032: stelem.i4 IL_0033: dup IL_0034: ldc.i4.1 IL_0035: ldc.i4.2 IL_0036: stelem.i4 IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.3 IL_003a: stelem.i4 IL_003b: stloc.3 IL_003c: ldloc.3 IL_003d: ldc.i4.0 IL_003e: ldelema ""int"" IL_0043: stloc.s V_4 IL_0045: ldloc.3 IL_0046: ldc.i4.0 IL_0047: ldelema ""int"" IL_004c: stloc.s V_5 IL_004e: ldnull IL_004f: stloc.s V_6 IL_0051: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0056: stloc.s V_7 IL_0058: ret } "); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.ICompilationTracker.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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { private interface ICompilationTracker { /// <summary> /// Returns true if this tracker currently either points to a compilation, has an in-progress /// compilation being computed, or has a skeleton reference. Note: this is simply a weak /// statement about the tracker at this exact moment in time. Immediately after this returns /// the tracker might change and may no longer have a final compilation (for example, if the /// retainer let go of it) or might not have an in-progress compilation (for example, if the /// background compiler finished with it). /// /// Because of the above limitations, this should only be used by clients as a weak form of /// information about the tracker. For example, a client may see that a tracker has no /// compilation and may choose to throw it away knowing that it could be reconstructed at a /// later point if necessary. /// </summary> bool HasCompilation { get; } ProjectState ProjectState { get; } ICompilationTracker Clone(); /// <summary> /// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the /// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see /// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>. /// </summary> /// <remarks> /// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered /// when answering this question. In other words, if <paramref name="symbol"/> is an <see /// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only /// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is /// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any /// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for /// any of the references of the <see cref="Compilation.References"/>. /// </remarks> bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken); ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, bool clone = false, CancellationToken cancellationToken = default); ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken); Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken); /// <summary> /// Get a metadata reference to this compilation info's compilation with respect to /// another project. For cross language references produce a skeletal assembly. If the /// compilation is not available, it is built. If a skeletal assembly reference is /// needed and does not exist, it is also built. /// </summary> Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken); CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference); ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken); IEnumerable<SyntaxTree>? GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken); Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken); bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation); SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { private interface ICompilationTracker { /// <summary> /// Returns true if this tracker currently either points to a compilation, has an in-progress /// compilation being computed, or has a skeleton reference. Note: this is simply a weak /// statement about the tracker at this exact moment in time. Immediately after this returns /// the tracker might change and may no longer have a final compilation (for example, if the /// retainer let go of it) or might not have an in-progress compilation (for example, if the /// background compiler finished with it). /// /// Because of the above limitations, this should only be used by clients as a weak form of /// information about the tracker. For example, a client may see that a tracker has no /// compilation and may choose to throw it away knowing that it could be reconstructed at a /// later point if necessary. /// </summary> bool HasCompilation { get; } ProjectState ProjectState { get; } ICompilationTracker Clone(); /// <summary> /// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the /// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see /// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>. /// </summary> /// <remarks> /// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered /// when answering this question. In other words, if <paramref name="symbol"/> is an <see /// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only /// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is /// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any /// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for /// any of the references of the <see cref="Compilation.References"/>. /// </remarks> bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken); ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, bool clone = false, CancellationToken cancellationToken = default); ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken); Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken); /// <summary> /// Get a metadata reference to this compilation info's compilation with respect to /// another project. For cross language references produce a skeletal assembly. If the /// compilation is not available, it is built. If a skeletal assembly reference is /// needed and does not exist, it is also built. /// </summary> Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken); CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference); ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken); IEnumerable<SyntaxTree>? GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken); Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken); bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation); SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/CSharp/Portable/Organizing/Organizers/MemberDeclarationsOrganizer.Comparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { internal partial class MemberDeclarationsOrganizer { private class Comparer : IComparer<MemberDeclarationSyntax> { // TODO(cyrusn): Allow users to specify the ordering they want private enum OuterOrdering { Fields, EventFields, Constructors, Destructors, Properties, Events, Indexers, Operators, ConversionOperators, Methods, Types, Remaining } private enum InnerOrdering { StaticInstance, Accessibility, Name } private enum Accessibility { Public, Protected, ProtectedOrInternal, Internal, Private } public int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y) { if (x == y) { return 0; } var xOuterOrdering = GetOuterOrdering(x); var yOuterOrdering = GetOuterOrdering(y); var compare = xOuterOrdering - yOuterOrdering; if (compare != 0) { return compare; } if (xOuterOrdering == OuterOrdering.Remaining) { return 1; } else if (yOuterOrdering == OuterOrdering.Remaining) { return -1; } if (xOuterOrdering == OuterOrdering.Fields || yOuterOrdering == OuterOrdering.Fields) { // Fields with initializers can't be reordered relative to // themselves due to ordering issues. var xHasInitializer = ((FieldDeclarationSyntax)x).Declaration.Variables.Any(v => v.Initializer != null); var yHasInitializer = ((FieldDeclarationSyntax)y).Declaration.Variables.Any(v => v.Initializer != null); if (xHasInitializer && yHasInitializer) { return 0; } } var xIsStatic = x.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword); var yIsStatic = y.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword); if ((compare = Comparer<bool>.Default.Inverse().Compare(xIsStatic, yIsStatic)) != 0) { return compare; } var xAccessibility = GetAccessibility(x); var yAccessibility = GetAccessibility(y); if ((compare = xAccessibility - yAccessibility) != 0) { return compare; } var xName = ShouldCompareByName(x) ? x.GetNameToken() : default; var yName = ShouldCompareByName(y) ? y.GetNameToken() : default; if ((compare = TokenComparer.NormalInstance.Compare(xName, yName)) != 0) { return compare; } // Their names were the same. Order them by arity at this point. return x.GetArity() - y.GetArity(); } private static Accessibility GetAccessibility(MemberDeclarationSyntax x) { var xModifiers = x.GetModifiers(); if (xModifiers.Any(t => t.Kind() == SyntaxKind.PublicKeyword)) { return Accessibility.Public; } else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword) && xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword)) { return Accessibility.ProtectedOrInternal; } else if (xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword)) { return Accessibility.Internal; } else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword)) { return Accessibility.Protected; } else { return Accessibility.Private; } } private static OuterOrdering GetOuterOrdering(MemberDeclarationSyntax x) { switch (x.Kind()) { case SyntaxKind.FieldDeclaration: return OuterOrdering.Fields; case SyntaxKind.EventFieldDeclaration: return OuterOrdering.EventFields; case SyntaxKind.ConstructorDeclaration: return OuterOrdering.Constructors; case SyntaxKind.DestructorDeclaration: return OuterOrdering.Destructors; case SyntaxKind.PropertyDeclaration: return OuterOrdering.Properties; case SyntaxKind.EventDeclaration: return OuterOrdering.Events; case SyntaxKind.IndexerDeclaration: return OuterOrdering.Indexers; case SyntaxKind.OperatorDeclaration: return OuterOrdering.Operators; case SyntaxKind.ConversionOperatorDeclaration: return OuterOrdering.ConversionOperators; case SyntaxKind.MethodDeclaration: return OuterOrdering.Methods; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return OuterOrdering.Types; default: return OuterOrdering.Remaining; } } private static bool ShouldCompareByName(MemberDeclarationSyntax x) { // Constructors, destructors, indexers and operators should not be sorted by name. // Note: Conversion operators should not be sorted by name either, but it's not // necessary to deal with that here, because GetNameToken cannot return a // name for them (there's only a NameSyntax, not a Token). switch (x.Kind()) { case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: return false; default: return true; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { internal partial class MemberDeclarationsOrganizer { private class Comparer : IComparer<MemberDeclarationSyntax> { // TODO(cyrusn): Allow users to specify the ordering they want private enum OuterOrdering { Fields, EventFields, Constructors, Destructors, Properties, Events, Indexers, Operators, ConversionOperators, Methods, Types, Remaining } private enum InnerOrdering { StaticInstance, Accessibility, Name } private enum Accessibility { Public, Protected, ProtectedOrInternal, Internal, Private } public int Compare(MemberDeclarationSyntax x, MemberDeclarationSyntax y) { if (x == y) { return 0; } var xOuterOrdering = GetOuterOrdering(x); var yOuterOrdering = GetOuterOrdering(y); var compare = xOuterOrdering - yOuterOrdering; if (compare != 0) { return compare; } if (xOuterOrdering == OuterOrdering.Remaining) { return 1; } else if (yOuterOrdering == OuterOrdering.Remaining) { return -1; } if (xOuterOrdering == OuterOrdering.Fields || yOuterOrdering == OuterOrdering.Fields) { // Fields with initializers can't be reordered relative to // themselves due to ordering issues. var xHasInitializer = ((FieldDeclarationSyntax)x).Declaration.Variables.Any(v => v.Initializer != null); var yHasInitializer = ((FieldDeclarationSyntax)y).Declaration.Variables.Any(v => v.Initializer != null); if (xHasInitializer && yHasInitializer) { return 0; } } var xIsStatic = x.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword); var yIsStatic = y.GetModifiers().Any(t => t.Kind() == SyntaxKind.StaticKeyword); if ((compare = Comparer<bool>.Default.Inverse().Compare(xIsStatic, yIsStatic)) != 0) { return compare; } var xAccessibility = GetAccessibility(x); var yAccessibility = GetAccessibility(y); if ((compare = xAccessibility - yAccessibility) != 0) { return compare; } var xName = ShouldCompareByName(x) ? x.GetNameToken() : default; var yName = ShouldCompareByName(y) ? y.GetNameToken() : default; if ((compare = TokenComparer.NormalInstance.Compare(xName, yName)) != 0) { return compare; } // Their names were the same. Order them by arity at this point. return x.GetArity() - y.GetArity(); } private static Accessibility GetAccessibility(MemberDeclarationSyntax x) { var xModifiers = x.GetModifiers(); if (xModifiers.Any(t => t.Kind() == SyntaxKind.PublicKeyword)) { return Accessibility.Public; } else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword) && xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword)) { return Accessibility.ProtectedOrInternal; } else if (xModifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword)) { return Accessibility.Internal; } else if (xModifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword)) { return Accessibility.Protected; } else { return Accessibility.Private; } } private static OuterOrdering GetOuterOrdering(MemberDeclarationSyntax x) { switch (x.Kind()) { case SyntaxKind.FieldDeclaration: return OuterOrdering.Fields; case SyntaxKind.EventFieldDeclaration: return OuterOrdering.EventFields; case SyntaxKind.ConstructorDeclaration: return OuterOrdering.Constructors; case SyntaxKind.DestructorDeclaration: return OuterOrdering.Destructors; case SyntaxKind.PropertyDeclaration: return OuterOrdering.Properties; case SyntaxKind.EventDeclaration: return OuterOrdering.Events; case SyntaxKind.IndexerDeclaration: return OuterOrdering.Indexers; case SyntaxKind.OperatorDeclaration: return OuterOrdering.Operators; case SyntaxKind.ConversionOperatorDeclaration: return OuterOrdering.ConversionOperators; case SyntaxKind.MethodDeclaration: return OuterOrdering.Methods; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return OuterOrdering.Types; default: return OuterOrdering.Remaining; } } private static bool ShouldCompareByName(MemberDeclarationSyntax x) { // Constructors, destructors, indexers and operators should not be sorted by name. // Note: Conversion operators should not be sorted by name either, but it's not // necessary to deal with that here, because GetNameToken cannot return a // name for them (there's only a NameSyntax, not a Token). switch (x.Kind()) { case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: return false; default: return true; } } } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/Server/VBCSCompilerTests/CompilerServerApiTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO.Pipes; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Moq; using Roslyn.Test.Utilities; using Xunit; using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; using Microsoft.CodeAnalysis.Test.Utilities; using static Microsoft.CodeAnalysis.CommandLine.BuildResponse; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class CompilerServerApiTest : TestBase { internal ICompilerServerLogger Logger { get; } public CompilerServerApiTest(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } private const string HelloWorldSourceText = @" using System; class Hello { static void Main() { Console.WriteLine(""Hello, world.""); } }"; private static Task TaskFromException(Exception e) { return TaskFromException<bool>(e); } private static Task<T> TaskFromException<T>(Exception e) { var source = new TaskCompletionSource<T>(); source.SetException(e); return source.Task; } private async Task<BuildRequest> CreateBuildRequest(string sourceText, TimeSpan? keepAlive = null) { var directory = Temp.CreateDirectory(); var file = directory.CreateFile("temp.cs"); await file.WriteAllTextAsync(sourceText); var builder = ImmutableArray.CreateBuilder<BuildRequest.Argument>(); if (keepAlive.HasValue) { builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.KeepAlive, argumentIndex: 0, value: keepAlive.Value.TotalSeconds.ToString())); } builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CurrentDirectory, argumentIndex: 0, value: directory.Path)); builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CommandLineArgument, argumentIndex: 0, value: file.Path)); return new BuildRequest( RequestLanguage.CSharpCompile, BuildProtocolConstants.GetCommitHash(), builder.ToImmutable()); } /// <summary> /// Run a C# compilation against the given source text using the provided named pipe name. /// </summary> private async Task<BuildResponse> RunCSharpCompile(string pipeName, string sourceText, TimeSpan? keepAlive = null) { using (var namedPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut)) { var buildRequest = await CreateBuildRequest(sourceText, keepAlive); namedPipe.Connect(Timeout.Infinite); await buildRequest.WriteAsync(namedPipe, default(CancellationToken)); return await BuildResponse.ReadAsync(namedPipe, default(CancellationToken)); } } private static Task<T> FromException<T>(Exception ex) { var source = new TaskCompletionSource<T>(); source.SetException(ex); return source.Task; } [Fact] public void MutexStopsServerStarting() { var pipeName = Guid.NewGuid().ToString("N"); var mutexName = BuildServerConnection.GetServerMutexName(pipeName); bool holdsMutex; using (var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out holdsMutex)) { Assert.True(holdsMutex); try { var host = new Mock<IClientConnectionHost>(MockBehavior.Strict); var result = BuildServerController.CreateAndRunServer( pipeName, clientConnectionHost: host.Object, keepAlive: null); Assert.Equal(CommonCompiler.Failed, result); } finally { mutex.ReleaseMutex(); } } } [Fact] public void MutexAcquiredWhenRunningServer() { var pipeName = Guid.NewGuid().ToString("N"); var mutexName = BuildServerConnection.GetServerMutexName(pipeName); var host = new TestableClientConnectionHost(); bool? wasServerMutexOpen = null; host.Add(() => { // Use a thread instead of Task to guarantee this code runs on a different // thread and we can validate the mutex state. var tcs = new TaskCompletionSource<IClientConnection>(); var thread = new Thread(_ => { wasServerMutexOpen = BuildServerConnection.WasServerMutexOpen(mutexName); var client = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(ProtocolUtil.EmptyCSharpBuildRequest), WriteBuildResponseFunc = (r, _) => Task.CompletedTask, }; tcs.SetResult(client); }); thread.Start(); return tcs.Task; }); host.Add(() => { var client = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(BuildRequest.CreateShutdown()), WriteBuildResponseFunc = (r, _) => Task.CompletedTask, }; return Task.FromResult<IClientConnection>(client); }); var result = BuildServerController.CreateAndRunServer( pipeName, clientConnectionHost: host, keepAlive: TimeSpan.FromMilliseconds(-1)); Assert.Equal(CommonCompiler.Succeeded, result); Assert.True(wasServerMutexOpen); } [WorkItem(13995, "https://github.com/dotnet/roslyn/issues/13995")] [Fact] public async Task RejectEmptyTempPath() { using var temp = new TempRoot(); using var serverData = await ServerUtil.CreateServer(Logger); var request = BuildRequest.Create(RequestLanguage.CSharpCompile, workingDirectory: temp.CreateDirectory().Path, tempDirectory: null, compilerHash: BuildProtocolConstants.GetCommitHash(), libDirectory: null, args: Array.Empty<string>()); var response = await serverData.SendAsync(request); Assert.Equal(ResponseType.Rejected, response.Type); } [Fact] public async Task IncorrectServerHashReturnsIncorrectHashResponse() { using var serverData = await ServerUtil.CreateServer(Logger); var buildResponse = await serverData.SendAsync(new BuildRequest(RequestLanguage.CSharpCompile, "abc", new List<BuildRequest.Argument> { })); Assert.Equal(BuildResponse.ResponseType.IncorrectHash, buildResponse.Type); } [ConditionalFact(typeof(WindowsDesktopOnly))] [WorkItem(33452, "https://github.com/dotnet/roslyn/issues/33452")] public void QuotePipeName_Desktop() { var serverInfo = BuildServerConnection.GetServerProcessInfo(@"q:\tools", "name with space"); Assert.Equal(@"q:\tools\VBCSCompiler.exe", serverInfo.processFilePath); Assert.Equal(@"q:\tools\VBCSCompiler.exe", serverInfo.toolFilePath); Assert.Equal(@"""-pipename:name with space""", serverInfo.commandLineArguments); } [ConditionalFact(typeof(CoreClrOnly))] [WorkItem(33452, "https://github.com/dotnet/roslyn/issues/33452")] public void QuotePipeName_CoreClr() { var toolDir = ExecutionConditionUtil.IsWindows ? @"q:\tools" : "/tools"; var serverInfo = BuildServerConnection.GetServerProcessInfo(toolDir, "name with space"); var vbcsFilePath = Path.Combine(toolDir, "VBCSCompiler.dll"); Assert.Equal(vbcsFilePath, serverInfo.toolFilePath); Assert.Equal($@"exec ""{vbcsFilePath}"" ""-pipename:name with space""", serverInfo.commandLineArguments); } [Theory] [InlineData(@"OLqrNgkgZRf14qL91MdaUn8coiKckUIZCIEkpy0Lt18", "name with space", true, "basename")] [InlineData(@"8VDiJptv892LtWpeN86z76_YI0Yg0BV6j0SOv8CjQVA", @"ha""ha", true, "basename")] [InlineData(@"wKSU9psJMbkw+5+TFKLEf94aeslpEb3dDRpAw+9j4nw", @"jared", true, @"ha""ha")] [InlineData(@"0BDP4_GPWYQh9J_BknwhS9uAZAF_64PK4_VnNsddGZE", @"jared", false, @"ha""ha")] [InlineData(@"XroHfrjD1FTk7PcXcif2hZdmlVH_L0Pg+RUX01d_uQc", @"jared", false, @"ha\ha")] public void GetPipeNameCore(string expectedName, string userName, bool isAdmin, string compilerExeDir) { Assert.Equal(expectedName, BuildServerConnection.GetPipeName(userName, isAdmin, compilerExeDir)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO.Pipes; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Moq; using Roslyn.Test.Utilities; using Xunit; using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; using Microsoft.CodeAnalysis.Test.Utilities; using static Microsoft.CodeAnalysis.CommandLine.BuildResponse; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class CompilerServerApiTest : TestBase { internal ICompilerServerLogger Logger { get; } public CompilerServerApiTest(ITestOutputHelper testOutputHelper) { Logger = new XunitCompilerServerLogger(testOutputHelper); } private const string HelloWorldSourceText = @" using System; class Hello { static void Main() { Console.WriteLine(""Hello, world.""); } }"; private static Task TaskFromException(Exception e) { return TaskFromException<bool>(e); } private static Task<T> TaskFromException<T>(Exception e) { var source = new TaskCompletionSource<T>(); source.SetException(e); return source.Task; } private async Task<BuildRequest> CreateBuildRequest(string sourceText, TimeSpan? keepAlive = null) { var directory = Temp.CreateDirectory(); var file = directory.CreateFile("temp.cs"); await file.WriteAllTextAsync(sourceText); var builder = ImmutableArray.CreateBuilder<BuildRequest.Argument>(); if (keepAlive.HasValue) { builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.KeepAlive, argumentIndex: 0, value: keepAlive.Value.TotalSeconds.ToString())); } builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CurrentDirectory, argumentIndex: 0, value: directory.Path)); builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CommandLineArgument, argumentIndex: 0, value: file.Path)); return new BuildRequest( RequestLanguage.CSharpCompile, BuildProtocolConstants.GetCommitHash(), builder.ToImmutable()); } /// <summary> /// Run a C# compilation against the given source text using the provided named pipe name. /// </summary> private async Task<BuildResponse> RunCSharpCompile(string pipeName, string sourceText, TimeSpan? keepAlive = null) { using (var namedPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut)) { var buildRequest = await CreateBuildRequest(sourceText, keepAlive); namedPipe.Connect(Timeout.Infinite); await buildRequest.WriteAsync(namedPipe, default(CancellationToken)); return await BuildResponse.ReadAsync(namedPipe, default(CancellationToken)); } } private static Task<T> FromException<T>(Exception ex) { var source = new TaskCompletionSource<T>(); source.SetException(ex); return source.Task; } [Fact] public void MutexStopsServerStarting() { var pipeName = Guid.NewGuid().ToString("N"); var mutexName = BuildServerConnection.GetServerMutexName(pipeName); bool holdsMutex; using (var mutex = new Mutex(initiallyOwned: true, name: mutexName, createdNew: out holdsMutex)) { Assert.True(holdsMutex); try { var host = new Mock<IClientConnectionHost>(MockBehavior.Strict); var result = BuildServerController.CreateAndRunServer( pipeName, clientConnectionHost: host.Object, keepAlive: null); Assert.Equal(CommonCompiler.Failed, result); } finally { mutex.ReleaseMutex(); } } } [Fact] public void MutexAcquiredWhenRunningServer() { var pipeName = Guid.NewGuid().ToString("N"); var mutexName = BuildServerConnection.GetServerMutexName(pipeName); var host = new TestableClientConnectionHost(); bool? wasServerMutexOpen = null; host.Add(() => { // Use a thread instead of Task to guarantee this code runs on a different // thread and we can validate the mutex state. var tcs = new TaskCompletionSource<IClientConnection>(); var thread = new Thread(_ => { wasServerMutexOpen = BuildServerConnection.WasServerMutexOpen(mutexName); var client = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(ProtocolUtil.EmptyCSharpBuildRequest), WriteBuildResponseFunc = (r, _) => Task.CompletedTask, }; tcs.SetResult(client); }); thread.Start(); return tcs.Task; }); host.Add(() => { var client = new TestableClientConnection() { ReadBuildRequestFunc = _ => Task.FromResult(BuildRequest.CreateShutdown()), WriteBuildResponseFunc = (r, _) => Task.CompletedTask, }; return Task.FromResult<IClientConnection>(client); }); var result = BuildServerController.CreateAndRunServer( pipeName, clientConnectionHost: host, keepAlive: TimeSpan.FromMilliseconds(-1)); Assert.Equal(CommonCompiler.Succeeded, result); Assert.True(wasServerMutexOpen); } [WorkItem(13995, "https://github.com/dotnet/roslyn/issues/13995")] [Fact] public async Task RejectEmptyTempPath() { using var temp = new TempRoot(); using var serverData = await ServerUtil.CreateServer(Logger); var request = BuildRequest.Create(RequestLanguage.CSharpCompile, workingDirectory: temp.CreateDirectory().Path, tempDirectory: null, compilerHash: BuildProtocolConstants.GetCommitHash(), libDirectory: null, args: Array.Empty<string>()); var response = await serverData.SendAsync(request); Assert.Equal(ResponseType.Rejected, response.Type); } [Fact] public async Task IncorrectServerHashReturnsIncorrectHashResponse() { using var serverData = await ServerUtil.CreateServer(Logger); var buildResponse = await serverData.SendAsync(new BuildRequest(RequestLanguage.CSharpCompile, "abc", new List<BuildRequest.Argument> { })); Assert.Equal(BuildResponse.ResponseType.IncorrectHash, buildResponse.Type); } [ConditionalFact(typeof(WindowsDesktopOnly))] [WorkItem(33452, "https://github.com/dotnet/roslyn/issues/33452")] public void QuotePipeName_Desktop() { var serverInfo = BuildServerConnection.GetServerProcessInfo(@"q:\tools", "name with space"); Assert.Equal(@"q:\tools\VBCSCompiler.exe", serverInfo.processFilePath); Assert.Equal(@"q:\tools\VBCSCompiler.exe", serverInfo.toolFilePath); Assert.Equal(@"""-pipename:name with space""", serverInfo.commandLineArguments); } [ConditionalFact(typeof(CoreClrOnly))] [WorkItem(33452, "https://github.com/dotnet/roslyn/issues/33452")] public void QuotePipeName_CoreClr() { var toolDir = ExecutionConditionUtil.IsWindows ? @"q:\tools" : "/tools"; var serverInfo = BuildServerConnection.GetServerProcessInfo(toolDir, "name with space"); var vbcsFilePath = Path.Combine(toolDir, "VBCSCompiler.dll"); Assert.Equal(vbcsFilePath, serverInfo.toolFilePath); Assert.Equal($@"exec ""{vbcsFilePath}"" ""-pipename:name with space""", serverInfo.commandLineArguments); } [Theory] [InlineData(@"OLqrNgkgZRf14qL91MdaUn8coiKckUIZCIEkpy0Lt18", "name with space", true, "basename")] [InlineData(@"8VDiJptv892LtWpeN86z76_YI0Yg0BV6j0SOv8CjQVA", @"ha""ha", true, "basename")] [InlineData(@"wKSU9psJMbkw+5+TFKLEf94aeslpEb3dDRpAw+9j4nw", @"jared", true, @"ha""ha")] [InlineData(@"0BDP4_GPWYQh9J_BknwhS9uAZAF_64PK4_VnNsddGZE", @"jared", false, @"ha""ha")] [InlineData(@"XroHfrjD1FTk7PcXcif2hZdmlVH_L0Pg+RUX01d_uQc", @"jared", false, @"ha\ha")] public void GetPipeNameCore(string expectedName, string userName, bool isAdmin, string compilerExeDir) { Assert.Equal(expectedName, BuildServerConnection.GetPipeName(userName, isAdmin, compilerExeDir)); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/IntegrationTest/TestUtilities/WellKnownTagNames.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { public class WellKnownTagNames { public const string MarkerFormatDefinition_HighlightedReference = "MarkerFormatDefinition/HighlightedReference"; public const string MarkerFormatDefinition_HighlightedDefinition = "MarkerFormatDefinition/HighlightedDefinition"; public const string MarkerFormatDefinition_HighlightedWrittenReference = "MarkerFormatDefinition/HighlightedWrittenReference"; public static Type? GetTagTypeByName(string typeName) { switch (typeName) { case MarkerFormatDefinition_HighlightedReference: return typeof(ReferenceHighlightTag); case MarkerFormatDefinition_HighlightedDefinition: return typeof(DefinitionHighlightTag); case MarkerFormatDefinition_HighlightedWrittenReference: return typeof(WrittenReferenceHighlightTag); default: return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { public class WellKnownTagNames { public const string MarkerFormatDefinition_HighlightedReference = "MarkerFormatDefinition/HighlightedReference"; public const string MarkerFormatDefinition_HighlightedDefinition = "MarkerFormatDefinition/HighlightedDefinition"; public const string MarkerFormatDefinition_HighlightedWrittenReference = "MarkerFormatDefinition/HighlightedWrittenReference"; public static Type? GetTagTypeByName(string typeName) { switch (typeName) { case MarkerFormatDefinition_HighlightedReference: return typeof(ReferenceHighlightTag); case MarkerFormatDefinition_HighlightedDefinition: return typeof(DefinitionHighlightTag); case MarkerFormatDefinition_HighlightedWrittenReference: return typeof(WrittenReferenceHighlightTag); default: return null; } } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/CSharp/Portable/ExtractMethod/CSharpExtractMethodService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { [Export(typeof(IExtractMethodService)), Shared] [ExportLanguageService(typeof(IExtractMethodService), LanguageNames.CSharp)] internal class CSharpExtractMethodService : AbstractExtractMethodService<CSharpSelectionValidator, CSharpMethodExtractor, CSharpSelectionResult> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpExtractMethodService() { } protected override CSharpSelectionValidator CreateSelectionValidator(SemanticDocument document, TextSpan textSpan, OptionSet options) => new CSharpSelectionValidator(document, textSpan, options); protected override CSharpMethodExtractor CreateMethodExtractor(CSharpSelectionResult selectionResult, bool localFunction) => new CSharpMethodExtractor(selectionResult, localFunction); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { [Export(typeof(IExtractMethodService)), Shared] [ExportLanguageService(typeof(IExtractMethodService), LanguageNames.CSharp)] internal class CSharpExtractMethodService : AbstractExtractMethodService<CSharpSelectionValidator, CSharpMethodExtractor, CSharpSelectionResult> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpExtractMethodService() { } protected override CSharpSelectionValidator CreateSelectionValidator(SemanticDocument document, TextSpan textSpan, OptionSet options) => new CSharpSelectionValidator(document, textSpan, options); protected override CSharpMethodExtractor CreateMethodExtractor(CSharpSelectionResult selectionResult, bool localFunction) => new CSharpMethodExtractor(selectionResult, localFunction); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionStorageLocation2.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.Options { /// <summary> /// The base type of all types that specify where options are stored. /// </summary> internal abstract class OptionStorageLocation2 #if !CODE_STYLE : OptionStorageLocation #endif { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Options { /// <summary> /// The base type of all types that specify where options are stored. /// </summary> internal abstract class OptionStorageLocation2 #if !CODE_STYLE : OptionStorageLocation #endif { } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Interactive/HostTest/InteractiveHostDesktopInitTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. extern alias InteractiveHost; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; [Trait(Traits.Feature, Traits.Features.InteractiveHost)] public sealed class InteractiveHostDesktopInitTests : AbstractInteractiveHostTests { internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Desktop32; internal override bool UseDefaultInitializationFile => true; [Fact] public async Task SearchPaths1() { var fxDir = await GetHostRuntimeDirectoryAsync(); var dll = Temp.CreateFile(extension: ".dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01); var srcDir = Temp.CreateDirectory(); var dllDir = Path.GetDirectoryName(dll.Path)!; srcDir.CreateFile("goo.csx").WriteAllText("ReferencePaths.Add(@\"" + dllDir + "\");"); // print default: await Host.ExecuteAsync(@"ReferencePaths"); var output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(fxDir), output); await Host.ExecuteAsync(@"SourcePaths"); output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(), output); // add and test if added: await Host.ExecuteAsync("SourcePaths.Add(@\"" + srcDir + "\");"); await Host.ExecuteAsync(@"SourcePaths"); output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(srcDir.Path), output); // execute file (uses modified search paths), the file adds a reference path await Host.ExecuteFileAsync("goo.csx"); await Host.ExecuteAsync(@"ReferencePaths"); output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(fxDir, dllDir), output); await Host.AddReferenceAsync(Path.GetFileName(dll.Path)); await Host.ExecuteAsync(@"typeof(Metadata.ICSProp)"); var error = await ReadErrorOutputToEnd(); output = await ReadOutputToEnd(); Assert.Equal("", error); Assert.Equal("[Metadata.ICSProp]\r\n", output); } [Fact] public async Task AddReference_AssemblyAlreadyLoaded() { var result = await LoadReference("System.Core"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences("", output); Assert.True(result); result = await LoadReference("System.Core.dll"); output = await ReadOutputToEnd(); error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences("", output); Assert.True(result); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. extern alias InteractiveHost; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { using InteractiveHost::Microsoft.CodeAnalysis.Interactive; [Trait(Traits.Feature, Traits.Features.InteractiveHost)] public sealed class InteractiveHostDesktopInitTests : AbstractInteractiveHostTests { internal override InteractiveHostPlatform DefaultPlatform => InteractiveHostPlatform.Desktop32; internal override bool UseDefaultInitializationFile => true; [Fact] public async Task SearchPaths1() { var fxDir = await GetHostRuntimeDirectoryAsync(); var dll = Temp.CreateFile(extension: ".dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01); var srcDir = Temp.CreateDirectory(); var dllDir = Path.GetDirectoryName(dll.Path)!; srcDir.CreateFile("goo.csx").WriteAllText("ReferencePaths.Add(@\"" + dllDir + "\");"); // print default: await Host.ExecuteAsync(@"ReferencePaths"); var output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(fxDir), output); await Host.ExecuteAsync(@"SourcePaths"); output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(), output); // add and test if added: await Host.ExecuteAsync("SourcePaths.Add(@\"" + srcDir + "\");"); await Host.ExecuteAsync(@"SourcePaths"); output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(srcDir.Path), output); // execute file (uses modified search paths), the file adds a reference path await Host.ExecuteFileAsync("goo.csx"); await Host.ExecuteAsync(@"ReferencePaths"); output = await ReadOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences(PrintSearchPaths(fxDir, dllDir), output); await Host.AddReferenceAsync(Path.GetFileName(dll.Path)); await Host.ExecuteAsync(@"typeof(Metadata.ICSProp)"); var error = await ReadErrorOutputToEnd(); output = await ReadOutputToEnd(); Assert.Equal("", error); Assert.Equal("[Metadata.ICSProp]\r\n", output); } [Fact] public async Task AddReference_AssemblyAlreadyLoaded() { var result = await LoadReference("System.Core"); var output = await ReadOutputToEnd(); var error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences("", output); Assert.True(result); result = await LoadReference("System.Core.dll"); output = await ReadOutputToEnd(); error = await ReadErrorOutputToEnd(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", error); AssertEx.AssertEqualToleratingWhitespaceDifferences("", output); Assert.True(result); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Dependencies/Collections/Internal/ThrowHelper.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. // This file defines an internal class used to throw exceptions in BCL code. // The main purpose is to reduce code size. // // The old way to throw an exception generates quite a lot IL code and assembly code. // Following is an example: // C# source // throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); // IL code: // IL_0003: ldstr "key" // IL_0008: ldstr "ArgumentNull_Key" // IL_000d: call string System.Environment::GetResourceString(string) // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string) // IL_0017: throw // which is 21bytes in IL. // // So we want to get rid of the ldstr and call to Environment.GetResource in IL. // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the // argument name and resource name in a small integer. The source code will be changed to // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); // // The IL code will be 7 bytes. // IL_0008: ldc.i4.4 // IL_0009: ldc.i4.4 // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) // IL_000f: ldarg.0 // // This will also reduce the Jitted code size a lot. // // It is very important we do this for generic classes because we can easily generate the same code // multiple times for different instantiation. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Collections.Internal { internal static class ThrowHelper { [DoesNotReturn] internal static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException() { throw new ArgumentOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_IndexException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } [DoesNotReturn] internal static void ThrowArgumentException_BadComparer(object? comparer) { throw new ArgumentException(string.Format(SR.Arg_BogusIComparer, comparer)); } [DoesNotReturn] internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() { throw GetArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() { throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } [DoesNotReturn] internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() { throw GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } [DoesNotReturn] internal static void ThrowWrongKeyTypeArgumentException<T>(T key, Type targetType) { // Generic key to move the boxing to the right hand side of throw throw GetWrongKeyTypeArgumentException((object?)key, targetType); } [DoesNotReturn] internal static void ThrowWrongValueTypeArgumentException<T>(T value, Type targetType) { // Generic key to move the boxing to the right hand side of throw throw GetWrongValueTypeArgumentException((object?)value, targetType); } private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object? key) { return new ArgumentException(string.Format(SR.Argument_AddingDuplicateWithKey, key)); } [DoesNotReturn] internal static void ThrowAddingDuplicateWithKeyArgumentException<T>(T key) { // Generic key to move the boxing to the right hand side of throw throw GetAddingDuplicateWithKeyArgumentException((object?)key); } [DoesNotReturn] internal static void ThrowKeyNotFoundException<T>(T key) { // Generic key to move the boxing to the right hand side of throw throw GetKeyNotFoundException((object?)key); } [DoesNotReturn] internal static void ThrowArgumentException(ExceptionResource resource) { throw GetArgumentException(resource); } private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw GetArgumentNullException(argument); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, resource); } [DoesNotReturn] internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) { throw new InvalidOperationException(GetResourceString(resource), e); } [DoesNotReturn] internal static void ThrowNotSupportedException(ExceptionResource resource) { throw new NotSupportedException(GetResourceString(resource)); } [DoesNotReturn] internal static void ThrowArgumentException_Argument_InvalidArrayType() { throw new ArgumentException(SR.Argument_InvalidArrayType); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } [DoesNotReturn] internal static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported() { throw new InvalidOperationException(SR.InvalidOperation_ConcurrentOperationsNotSupported); } private static ArgumentException GetArgumentException(ExceptionResource resource) { return new ArgumentException(GetResourceString(resource)); } private static ArgumentException GetWrongKeyTypeArgumentException(object? key, Type targetType) { return new ArgumentException(string.Format(SR.Arg_WrongType, key, targetType), nameof(key)); } private static ArgumentException GetWrongValueTypeArgumentException(object? value, Type targetType) { return new ArgumentException(string.Format(SR.Arg_WrongType, value, targetType), nameof(value)); } private static KeyNotFoundException GetKeyNotFoundException(object? key) { return new KeyNotFoundException(string.Format(SR.Arg_KeyNotFoundWithKey, key)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource)); } // Allow nulls for reference types and Nullable<U>, but not for value types. // Aggressively inline so the jit evaluates the if in place and either drops the call altogether // Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void IfNullAndNullsAreIllegalThenThrow<T>(object? value, ExceptionArgument argName) { // Note that default(T) is not equal to null for value types except when T is Nullable<U>. if (!(default(T) == null) && value == null) ThrowHelper.ThrowArgumentNullException(argName); } private static string GetArgumentName(ExceptionArgument argument) { switch (argument) { case ExceptionArgument.dictionary: return "dictionary"; case ExceptionArgument.array: return "array"; case ExceptionArgument.key: return "key"; case ExceptionArgument.value: return "value"; case ExceptionArgument.startIndex: return "startIndex"; case ExceptionArgument.index: return "index"; case ExceptionArgument.capacity: return "capacity"; case ExceptionArgument.collection: return "collection"; case ExceptionArgument.item: return "item"; case ExceptionArgument.converter: return "converter"; case ExceptionArgument.match: return "match"; case ExceptionArgument.count: return "count"; case ExceptionArgument.action: return "action"; case ExceptionArgument.comparison: return "comparison"; case ExceptionArgument.source: return "source"; case ExceptionArgument.length: return "length"; case ExceptionArgument.destinationArray: return "destinationArray"; default: Debug.Fail("The enum value is not defined, please check the ExceptionArgument Enum."); return ""; } } private static string GetResourceString(ExceptionResource resource) { switch (resource) { case ExceptionResource.ArgumentOutOfRange_Index: return SR.ArgumentOutOfRange_Index; case ExceptionResource.ArgumentOutOfRange_Count: return SR.ArgumentOutOfRange_Count; case ExceptionResource.Arg_ArrayPlusOffTooSmall: return SR.Arg_ArrayPlusOffTooSmall; case ExceptionResource.Arg_RankMultiDimNotSupported: return SR.Arg_RankMultiDimNotSupported; case ExceptionResource.Arg_NonZeroLowerBound: return SR.Arg_NonZeroLowerBound; case ExceptionResource.ArgumentOutOfRange_ListInsert: return SR.ArgumentOutOfRange_ListInsert; case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum: return SR.ArgumentOutOfRange_NeedNonNegNum; case ExceptionResource.ArgumentOutOfRange_SmallCapacity: return SR.ArgumentOutOfRange_SmallCapacity; case ExceptionResource.Argument_InvalidOffLen: return SR.Argument_InvalidOffLen; case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection: return SR.ArgumentOutOfRange_BiggerThanCollection; case ExceptionResource.NotSupported_KeyCollectionSet: return SR.NotSupported_KeyCollectionSet; case ExceptionResource.NotSupported_ValueCollectionSet: return SR.NotSupported_ValueCollectionSet; case ExceptionResource.InvalidOperation_IComparerFailed: return SR.InvalidOperation_IComparerFailed; default: Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum."); return ""; } } } // // The convention for this enum is using the argument name as the enum name // internal enum ExceptionArgument { dictionary, array, key, value, startIndex, index, capacity, collection, item, converter, match, count, action, comparison, source, length, destinationArray, } // // The convention for this enum is using the resource name as the enum name // internal enum ExceptionResource { ArgumentOutOfRange_Index, ArgumentOutOfRange_Count, Arg_ArrayPlusOffTooSmall, Arg_RankMultiDimNotSupported, Arg_NonZeroLowerBound, ArgumentOutOfRange_ListInsert, ArgumentOutOfRange_NeedNonNegNum, ArgumentOutOfRange_SmallCapacity, Argument_InvalidOffLen, ArgumentOutOfRange_BiggerThanCollection, NotSupported_KeyCollectionSet, NotSupported_ValueCollectionSet, InvalidOperation_IComparerFailed, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // This file defines an internal class used to throw exceptions in BCL code. // The main purpose is to reduce code size. // // The old way to throw an exception generates quite a lot IL code and assembly code. // Following is an example: // C# source // throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); // IL code: // IL_0003: ldstr "key" // IL_0008: ldstr "ArgumentNull_Key" // IL_000d: call string System.Environment::GetResourceString(string) // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string) // IL_0017: throw // which is 21bytes in IL. // // So we want to get rid of the ldstr and call to Environment.GetResource in IL. // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the // argument name and resource name in a small integer. The source code will be changed to // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); // // The IL code will be 7 bytes. // IL_0008: ldc.i4.4 // IL_0009: ldc.i4.4 // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) // IL_000f: ldarg.0 // // This will also reduce the Jitted code size a lot. // // It is very important we do this for generic classes because we can easily generate the same code // multiple times for different instantiation. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.Collections.Internal { internal static class ThrowHelper { [DoesNotReturn] internal static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException() { throw new ArgumentOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_IndexException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } [DoesNotReturn] internal static void ThrowArgumentException_BadComparer(object? comparer) { throw new ArgumentException(string.Format(SR.Arg_BogusIComparer, comparer)); } [DoesNotReturn] internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() { throw GetArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() { throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } [DoesNotReturn] internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() { throw GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } [DoesNotReturn] internal static void ThrowWrongKeyTypeArgumentException<T>(T key, Type targetType) { // Generic key to move the boxing to the right hand side of throw throw GetWrongKeyTypeArgumentException((object?)key, targetType); } [DoesNotReturn] internal static void ThrowWrongValueTypeArgumentException<T>(T value, Type targetType) { // Generic key to move the boxing to the right hand side of throw throw GetWrongValueTypeArgumentException((object?)value, targetType); } private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object? key) { return new ArgumentException(string.Format(SR.Argument_AddingDuplicateWithKey, key)); } [DoesNotReturn] internal static void ThrowAddingDuplicateWithKeyArgumentException<T>(T key) { // Generic key to move the boxing to the right hand side of throw throw GetAddingDuplicateWithKeyArgumentException((object?)key); } [DoesNotReturn] internal static void ThrowKeyNotFoundException<T>(T key) { // Generic key to move the boxing to the right hand side of throw throw GetKeyNotFoundException((object?)key); } [DoesNotReturn] internal static void ThrowArgumentException(ExceptionResource resource) { throw GetArgumentException(resource); } private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw GetArgumentNullException(argument); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, resource); } [DoesNotReturn] internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) { throw new InvalidOperationException(GetResourceString(resource), e); } [DoesNotReturn] internal static void ThrowNotSupportedException(ExceptionResource resource) { throw new NotSupportedException(GetResourceString(resource)); } [DoesNotReturn] internal static void ThrowArgumentException_Argument_InvalidArrayType() { throw new ArgumentException(SR.Argument_InvalidArrayType); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } [DoesNotReturn] internal static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported() { throw new InvalidOperationException(SR.InvalidOperation_ConcurrentOperationsNotSupported); } private static ArgumentException GetArgumentException(ExceptionResource resource) { return new ArgumentException(GetResourceString(resource)); } private static ArgumentException GetWrongKeyTypeArgumentException(object? key, Type targetType) { return new ArgumentException(string.Format(SR.Arg_WrongType, key, targetType), nameof(key)); } private static ArgumentException GetWrongValueTypeArgumentException(object? value, Type targetType) { return new ArgumentException(string.Format(SR.Arg_WrongType, value, targetType), nameof(value)); } private static KeyNotFoundException GetKeyNotFoundException(object? key) { return new KeyNotFoundException(string.Format(SR.Arg_KeyNotFoundWithKey, key)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource)); } // Allow nulls for reference types and Nullable<U>, but not for value types. // Aggressively inline so the jit evaluates the if in place and either drops the call altogether // Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void IfNullAndNullsAreIllegalThenThrow<T>(object? value, ExceptionArgument argName) { // Note that default(T) is not equal to null for value types except when T is Nullable<U>. if (!(default(T) == null) && value == null) ThrowHelper.ThrowArgumentNullException(argName); } private static string GetArgumentName(ExceptionArgument argument) { switch (argument) { case ExceptionArgument.dictionary: return "dictionary"; case ExceptionArgument.array: return "array"; case ExceptionArgument.key: return "key"; case ExceptionArgument.value: return "value"; case ExceptionArgument.startIndex: return "startIndex"; case ExceptionArgument.index: return "index"; case ExceptionArgument.capacity: return "capacity"; case ExceptionArgument.collection: return "collection"; case ExceptionArgument.item: return "item"; case ExceptionArgument.converter: return "converter"; case ExceptionArgument.match: return "match"; case ExceptionArgument.count: return "count"; case ExceptionArgument.action: return "action"; case ExceptionArgument.comparison: return "comparison"; case ExceptionArgument.source: return "source"; case ExceptionArgument.length: return "length"; case ExceptionArgument.destinationArray: return "destinationArray"; default: Debug.Fail("The enum value is not defined, please check the ExceptionArgument Enum."); return ""; } } private static string GetResourceString(ExceptionResource resource) { switch (resource) { case ExceptionResource.ArgumentOutOfRange_Index: return SR.ArgumentOutOfRange_Index; case ExceptionResource.ArgumentOutOfRange_Count: return SR.ArgumentOutOfRange_Count; case ExceptionResource.Arg_ArrayPlusOffTooSmall: return SR.Arg_ArrayPlusOffTooSmall; case ExceptionResource.Arg_RankMultiDimNotSupported: return SR.Arg_RankMultiDimNotSupported; case ExceptionResource.Arg_NonZeroLowerBound: return SR.Arg_NonZeroLowerBound; case ExceptionResource.ArgumentOutOfRange_ListInsert: return SR.ArgumentOutOfRange_ListInsert; case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum: return SR.ArgumentOutOfRange_NeedNonNegNum; case ExceptionResource.ArgumentOutOfRange_SmallCapacity: return SR.ArgumentOutOfRange_SmallCapacity; case ExceptionResource.Argument_InvalidOffLen: return SR.Argument_InvalidOffLen; case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection: return SR.ArgumentOutOfRange_BiggerThanCollection; case ExceptionResource.NotSupported_KeyCollectionSet: return SR.NotSupported_KeyCollectionSet; case ExceptionResource.NotSupported_ValueCollectionSet: return SR.NotSupported_ValueCollectionSet; case ExceptionResource.InvalidOperation_IComparerFailed: return SR.InvalidOperation_IComparerFailed; default: Debug.Fail("The enum value is not defined, please check the ExceptionResource Enum."); return ""; } } } // // The convention for this enum is using the argument name as the enum name // internal enum ExceptionArgument { dictionary, array, key, value, startIndex, index, capacity, collection, item, converter, match, count, action, comparison, source, length, destinationArray, } // // The convention for this enum is using the resource name as the enum name // internal enum ExceptionResource { ArgumentOutOfRange_Index, ArgumentOutOfRange_Count, Arg_ArrayPlusOffTooSmall, Arg_RankMultiDimNotSupported, Arg_NonZeroLowerBound, ArgumentOutOfRange_ListInsert, ArgumentOutOfRange_NeedNonNegNum, ArgumentOutOfRange_SmallCapacity, Argument_InvalidOffLen, ArgumentOutOfRange_BiggerThanCollection, NotSupported_KeyCollectionSet, NotSupported_ValueCollectionSet, InvalidOperation_IComparerFailed, } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/Core/Portable/Workspace/ProjectCacheService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// This service will implicitly cache previous Compilations used by each supported Workspace implementation. /// The number of Compilations cached is determined by <see cref="ImplicitCacheSize"/>. For now, we'll only /// support implicit caching for VS Workspaces (<see cref="WorkspaceKind.Host"/>), as caching is known to /// reduce latency in designer scenarios using the VS workspace. For other Workspace kinds, the cost of the /// cache is likely to outweigh the benefit (for example, in Misc File Workspace cases, we can end up holding /// onto a lot of memory even after a file is closed). We can opt in other kinds of Workspaces as needed. /// </summary> internal partial class ProjectCacheService : IProjectCacheHostService { internal const int ImplicitCacheSize = 3; private readonly object _gate = new(); private readonly Workspace _workspace; private readonly Dictionary<ProjectId, Cache> _activeCaches = new(); private readonly SimpleMRUCache? _implicitCache; private readonly ImplicitCacheMonitor? _implicitCacheMonitor; public ProjectCacheService(Workspace workspace) => _workspace = workspace; public ProjectCacheService(Workspace workspace, TimeSpan implicitCacheTimeout) { _workspace = workspace; _implicitCache = new SimpleMRUCache(); _implicitCacheMonitor = new ImplicitCacheMonitor(this, implicitCacheTimeout); } public bool IsImplicitCacheEmpty { get { lock (_gate) { return _implicitCache?.IsEmpty ?? false; } } } public void ClearImplicitCache() { lock (_gate) { _implicitCache?.Clear(); } } public void ClearExpiredImplicitCache(DateTime expirationTime) { lock (_gate) { _implicitCache?.ClearExpiredItems(expirationTime); } } public IDisposable EnableCaching(ProjectId key) { lock (_gate) { if (!_activeCaches.TryGetValue(key, out var cache)) { cache = new Cache(this, key); _activeCaches.Add(key, cache); } cache.Count++; return cache; } } [return: NotNullIfNotNull("instance")] public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T? instance) where T : class { lock (_gate) { if (_activeCaches.TryGetValue(key, out var cache)) { cache.CreateStrongReference(owner, instance); } else if (_implicitCache != null && !PartOfP2PReferences(key)) { RoslynDebug.Assert(_implicitCacheMonitor != null); _implicitCache.Touch(instance); _implicitCacheMonitor.Touch(); } return instance; } } private bool PartOfP2PReferences(ProjectId key) { if (_activeCaches.Count == 0 || _workspace == null) { return false; } var solution = _workspace.CurrentSolution; var graph = solution.GetProjectDependencyGraph(); foreach (var projectId in _activeCaches.Keys) { // this should be cheap. graph is cached every time project reference is updated. var p2pReferences = (ImmutableHashSet<ProjectId>)graph.GetProjectsThatThisProjectTransitivelyDependsOn(projectId); if (p2pReferences.Contains(key)) { return true; } } return false; } [return: NotNullIfNotNull("instance")] public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T? instance) where T : class { lock (_gate) { if (owner.CachedObject == null && _activeCaches.TryGetValue(key, out var cache)) { owner.CachedObject = instance; cache.CreateOwnerEntry(owner); } return instance; } } private void DisableCaching(ProjectId key, Cache cache) { lock (_gate) { cache.Count--; if (cache.Count == 0) { _activeCaches.Remove(key); cache.FreeOwnerEntries(); } } } private sealed class Cache : IDisposable { internal int Count; private readonly ProjectCacheService _cacheService; private readonly ProjectId _key; private ConditionalWeakTable<object, object?>? _cache = new(); private readonly List<WeakReference<ICachedObjectOwner>> _ownerObjects = new(); public Cache(ProjectCacheService cacheService, ProjectId key) { _cacheService = cacheService; _key = key; } public void Dispose() => _cacheService.DisableCaching(_key, this); internal void CreateStrongReference(object key, object? instance) { if (_cache == null) { throw new ObjectDisposedException(nameof(Cache)); } if (!_cache.TryGetValue(key, out _)) { _cache.Add(key, instance); } } internal void CreateOwnerEntry(ICachedObjectOwner owner) => _ownerObjects.Add(new WeakReference<ICachedObjectOwner>(owner)); internal void FreeOwnerEntries() { foreach (var entry in _ownerObjects) { if (entry.TryGetTarget(out var owner)) { owner.CachedObject = null; } } // Explicitly free our ConditionalWeakTable to make sure it's released. We have a number of places in the codebase // (in both tests and product code) that do using (service.EnableCaching), which implicitly returns a disposable instance // this type. The runtime in many cases disposes, but does not unroot, the underlying object after the the using block is exited. // This means the cache could still be rooting objects we don't expect it to be rooting by that point. By explicitly clearing // these out, we get the expected behavior. _cache = null; _ownerObjects.Clear(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// This service will implicitly cache previous Compilations used by each supported Workspace implementation. /// The number of Compilations cached is determined by <see cref="ImplicitCacheSize"/>. For now, we'll only /// support implicit caching for VS Workspaces (<see cref="WorkspaceKind.Host"/>), as caching is known to /// reduce latency in designer scenarios using the VS workspace. For other Workspace kinds, the cost of the /// cache is likely to outweigh the benefit (for example, in Misc File Workspace cases, we can end up holding /// onto a lot of memory even after a file is closed). We can opt in other kinds of Workspaces as needed. /// </summary> internal partial class ProjectCacheService : IProjectCacheHostService { internal const int ImplicitCacheSize = 3; private readonly object _gate = new(); private readonly Workspace _workspace; private readonly Dictionary<ProjectId, Cache> _activeCaches = new(); private readonly SimpleMRUCache? _implicitCache; private readonly ImplicitCacheMonitor? _implicitCacheMonitor; public ProjectCacheService(Workspace workspace) => _workspace = workspace; public ProjectCacheService(Workspace workspace, TimeSpan implicitCacheTimeout) { _workspace = workspace; _implicitCache = new SimpleMRUCache(); _implicitCacheMonitor = new ImplicitCacheMonitor(this, implicitCacheTimeout); } public bool IsImplicitCacheEmpty { get { lock (_gate) { return _implicitCache?.IsEmpty ?? false; } } } public void ClearImplicitCache() { lock (_gate) { _implicitCache?.Clear(); } } public void ClearExpiredImplicitCache(DateTime expirationTime) { lock (_gate) { _implicitCache?.ClearExpiredItems(expirationTime); } } public IDisposable EnableCaching(ProjectId key) { lock (_gate) { if (!_activeCaches.TryGetValue(key, out var cache)) { cache = new Cache(this, key); _activeCaches.Add(key, cache); } cache.Count++; return cache; } } [return: NotNullIfNotNull("instance")] public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T? instance) where T : class { lock (_gate) { if (_activeCaches.TryGetValue(key, out var cache)) { cache.CreateStrongReference(owner, instance); } else if (_implicitCache != null && !PartOfP2PReferences(key)) { RoslynDebug.Assert(_implicitCacheMonitor != null); _implicitCache.Touch(instance); _implicitCacheMonitor.Touch(); } return instance; } } private bool PartOfP2PReferences(ProjectId key) { if (_activeCaches.Count == 0 || _workspace == null) { return false; } var solution = _workspace.CurrentSolution; var graph = solution.GetProjectDependencyGraph(); foreach (var projectId in _activeCaches.Keys) { // this should be cheap. graph is cached every time project reference is updated. var p2pReferences = (ImmutableHashSet<ProjectId>)graph.GetProjectsThatThisProjectTransitivelyDependsOn(projectId); if (p2pReferences.Contains(key)) { return true; } } return false; } [return: NotNullIfNotNull("instance")] public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T? instance) where T : class { lock (_gate) { if (owner.CachedObject == null && _activeCaches.TryGetValue(key, out var cache)) { owner.CachedObject = instance; cache.CreateOwnerEntry(owner); } return instance; } } private void DisableCaching(ProjectId key, Cache cache) { lock (_gate) { cache.Count--; if (cache.Count == 0) { _activeCaches.Remove(key); cache.FreeOwnerEntries(); } } } private sealed class Cache : IDisposable { internal int Count; private readonly ProjectCacheService _cacheService; private readonly ProjectId _key; private ConditionalWeakTable<object, object?>? _cache = new(); private readonly List<WeakReference<ICachedObjectOwner>> _ownerObjects = new(); public Cache(ProjectCacheService cacheService, ProjectId key) { _cacheService = cacheService; _key = key; } public void Dispose() => _cacheService.DisableCaching(_key, this); internal void CreateStrongReference(object key, object? instance) { if (_cache == null) { throw new ObjectDisposedException(nameof(Cache)); } if (!_cache.TryGetValue(key, out _)) { _cache.Add(key, instance); } } internal void CreateOwnerEntry(ICachedObjectOwner owner) => _ownerObjects.Add(new WeakReference<ICachedObjectOwner>(owner)); internal void FreeOwnerEntries() { foreach (var entry in _ownerObjects) { if (entry.TryGetTarget(out var owner)) { owner.CachedObject = null; } } // Explicitly free our ConditionalWeakTable to make sure it's released. We have a number of places in the codebase // (in both tests and product code) that do using (service.EnableCaching), which implicitly returns a disposable instance // this type. The runtime in many cases disposes, but does not unroot, the underlying object after the the using block is exited. // This means the cache could still be rooting objects we don't expect it to be rooting by that point. By explicitly clearing // these out, we get the expected behavior. _cache = null; _ownerObjects.Clear(); } } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/VisualStudioWorkspace_InProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.OperationProgress; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Hosting.Diagnostics.Waiters; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class VisualStudioWorkspace_InProc : InProcComponent { private static readonly Guid RoslynPackageId = new Guid("6cf2e545-6109-4730-8883-cf43d7aec3e1"); private readonly VisualStudioWorkspace _visualStudioWorkspace; private VisualStudioWorkspace_InProc() { // we need to enable waiting service before we create workspace GetWaitingService().Enable(true); _visualStudioWorkspace = GetComponentModelService<VisualStudioWorkspace>(); } public static VisualStudioWorkspace_InProc Create() => new VisualStudioWorkspace_InProc(); public void SetOptionInfer(string projectName, bool value) => InvokeOnUIThread(cancellationToken => { var convertedValue = value ? 1 : 0; var project = GetProject(projectName); project.Properties.Item("OptionInfer").Value = convertedValue; }); private EnvDTE.Project GetProject(string nameOrFileName) => GetDTE().Solution.Projects.OfType<EnvDTE.Project>().First(p => string.Compare(p.FileName, nameOrFileName, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(p.Name, nameOrFileName, StringComparison.OrdinalIgnoreCase) == 0); public bool IsPrettyListingOn(string languageName) => _visualStudioWorkspace.Options.GetOption(FeatureOnOffOptions.PrettyListing, languageName); public void SetPrettyListing(string languageName, bool value) => InvokeOnUIThread(cancellationToken => { _visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption( FeatureOnOffOptions.PrettyListing, languageName, value)); }); public void EnableQuickInfo(bool value) => InvokeOnUIThread(cancellationToken => { _visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption( InternalFeatureOnOffOptions.QuickInfo, value)); }); public void SetPerLanguageOption(string optionName, string feature, string language, object value) { var option = GetOption(optionName, feature); var result = GetValue(value, option); var optionKey = new OptionKey(option, language); SetOption(optionKey, result); } public void SetOption(string optionName, string feature, object value) { var option = GetOption(optionName, feature); var result = GetValue(value, option); var optionKey = new OptionKey(option); SetOption(optionKey, result); } private static object GetValue(object value, IOption option) { object result; if (value is string stringValue) { result = TypeDescriptor.GetConverter(option.Type).ConvertFromString(stringValue); } else { result = value; } return result; } private IOption GetOption(string optionName, string feature) { var optionService = _visualStudioWorkspace.Services.GetRequiredService<IOptionService>(); var option = optionService.GetRegisteredOptions().FirstOrDefault(o => o.Feature == feature && o.Name == optionName); if (option == null) { throw new Exception($"Failed to find option with feature name '{feature}' and option name '{optionName}'"); } return option; } private void SetOption(OptionKey optionKey, object? result) => _visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption(optionKey, result)); private static TestingOnly_WaitingService GetWaitingService() => GetComponentModel().DefaultExportProvider.GetExport<TestingOnly_WaitingService>().Value; public void WaitForAsyncOperations(TimeSpan timeout, string featuresToWaitFor, bool waitForWorkspaceFirst = true) { if (waitForWorkspaceFirst || featuresToWaitFor == FeatureAttribute.Workspace) { WaitForProjectSystem(timeout); } GetWaitingService().WaitForAsyncOperations(timeout, featuresToWaitFor, waitForWorkspaceFirst); } public void WaitForAllAsyncOperations(TimeSpan timeout, params string[] featureNames) { if (featureNames.Contains(FeatureAttribute.Workspace)) { WaitForProjectSystem(timeout); } GetWaitingService().WaitForAllAsyncOperations(_visualStudioWorkspace, timeout, featureNames); } public void WaitForAllAsyncOperationsOrFail(TimeSpan timeout, params string[] featureNames) { try { WaitForAllAsyncOperations(timeout, featureNames); } catch (Exception e) { var listenerProvider = GetComponentModel().DefaultExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(); var messageBuilder = new StringBuilder("Failed to clean up listeners in a timely manner."); foreach (var token in ((AsynchronousOperationListenerProvider)listenerProvider).GetTokens()) { messageBuilder.AppendLine().Append($" {token}"); } Environment.FailFast("Terminating test process due to unrecoverable timeout.", new TimeoutException(messageBuilder.ToString(), e)); } } private static void WaitForProjectSystem(TimeSpan timeout) { var operationProgressStatus = InvokeOnUIThread(_ => GetGlobalService<SVsOperationProgress, IVsOperationProgressStatusService>()); var stageStatus = operationProgressStatus.GetStageStatus(CommonOperationProgressStageIds.Intellisense); stageStatus.WaitForCompletionAsync().Wait(timeout); } private static void LoadRoslynPackage() { var roslynPackageGuid = RoslynPackageId; var vsShell = GetGlobalService<SVsShell, IVsShell>(); var hresult = vsShell.LoadPackage(ref roslynPackageGuid, out _); Marshal.ThrowExceptionForHR(hresult); } public void CleanUpWorkspace() => InvokeOnUIThread(cancellationToken => { LoadRoslynPackage(); _visualStudioWorkspace.TestHookPartialSolutionsDisabled = true; }); /// <summary> /// Reset options that are manipulated by integration tests back to their default values. /// </summary> public void ResetOptions() { ResetOption(CompletionOptions.EnableArgumentCompletionSnippets); return; // Local function void ResetOption(IOption option) { if (option is IPerLanguageOption) { SetOption(new OptionKey(option, LanguageNames.CSharp), option.DefaultValue); SetOption(new OptionKey(option, LanguageNames.VisualBasic), option.DefaultValue); } else { SetOption(new OptionKey(option), option.DefaultValue); } } } public void CleanUpWaitingService() => InvokeOnUIThread(cancellationToken => { var provider = GetComponentModel().DefaultExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(); if (provider == null) { throw new InvalidOperationException("The test waiting service could not be located."); } GetWaitingService().EnableActiveTokenTracking(true); }); public void SetFeatureOption(string feature, string optionName, string language, string? valueString) => InvokeOnUIThread(cancellationToken => { var option = GetOption(optionName, feature); var value = TypeDescriptor.GetConverter(option.Type).ConvertFromString(valueString); var optionKey = string.IsNullOrWhiteSpace(language) ? new OptionKey(option) : new OptionKey(option, language); SetOption(optionKey, value); }); public string? GetWorkingFolder() { var service = _visualStudioWorkspace.Services.GetRequiredService<IPersistentStorageLocationService>(); return service.TryGetStorageLocation(_visualStudioWorkspace.CurrentSolution); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.OperationProgress; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Hosting.Diagnostics.Waiters; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class VisualStudioWorkspace_InProc : InProcComponent { private static readonly Guid RoslynPackageId = new Guid("6cf2e545-6109-4730-8883-cf43d7aec3e1"); private readonly VisualStudioWorkspace _visualStudioWorkspace; private VisualStudioWorkspace_InProc() { // we need to enable waiting service before we create workspace GetWaitingService().Enable(true); _visualStudioWorkspace = GetComponentModelService<VisualStudioWorkspace>(); } public static VisualStudioWorkspace_InProc Create() => new VisualStudioWorkspace_InProc(); public void SetOptionInfer(string projectName, bool value) => InvokeOnUIThread(cancellationToken => { var convertedValue = value ? 1 : 0; var project = GetProject(projectName); project.Properties.Item("OptionInfer").Value = convertedValue; }); private EnvDTE.Project GetProject(string nameOrFileName) => GetDTE().Solution.Projects.OfType<EnvDTE.Project>().First(p => string.Compare(p.FileName, nameOrFileName, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(p.Name, nameOrFileName, StringComparison.OrdinalIgnoreCase) == 0); public bool IsPrettyListingOn(string languageName) => _visualStudioWorkspace.Options.GetOption(FeatureOnOffOptions.PrettyListing, languageName); public void SetPrettyListing(string languageName, bool value) => InvokeOnUIThread(cancellationToken => { _visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption( FeatureOnOffOptions.PrettyListing, languageName, value)); }); public void EnableQuickInfo(bool value) => InvokeOnUIThread(cancellationToken => { _visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption( InternalFeatureOnOffOptions.QuickInfo, value)); }); public void SetPerLanguageOption(string optionName, string feature, string language, object value) { var option = GetOption(optionName, feature); var result = GetValue(value, option); var optionKey = new OptionKey(option, language); SetOption(optionKey, result); } public void SetOption(string optionName, string feature, object value) { var option = GetOption(optionName, feature); var result = GetValue(value, option); var optionKey = new OptionKey(option); SetOption(optionKey, result); } private static object GetValue(object value, IOption option) { object result; if (value is string stringValue) { result = TypeDescriptor.GetConverter(option.Type).ConvertFromString(stringValue); } else { result = value; } return result; } private IOption GetOption(string optionName, string feature) { var optionService = _visualStudioWorkspace.Services.GetRequiredService<IOptionService>(); var option = optionService.GetRegisteredOptions().FirstOrDefault(o => o.Feature == feature && o.Name == optionName); if (option == null) { throw new Exception($"Failed to find option with feature name '{feature}' and option name '{optionName}'"); } return option; } private void SetOption(OptionKey optionKey, object? result) => _visualStudioWorkspace.SetOptions(_visualStudioWorkspace.Options.WithChangedOption(optionKey, result)); private static TestingOnly_WaitingService GetWaitingService() => GetComponentModel().DefaultExportProvider.GetExport<TestingOnly_WaitingService>().Value; public void WaitForAsyncOperations(TimeSpan timeout, string featuresToWaitFor, bool waitForWorkspaceFirst = true) { if (waitForWorkspaceFirst || featuresToWaitFor == FeatureAttribute.Workspace) { WaitForProjectSystem(timeout); } GetWaitingService().WaitForAsyncOperations(timeout, featuresToWaitFor, waitForWorkspaceFirst); } public void WaitForAllAsyncOperations(TimeSpan timeout, params string[] featureNames) { if (featureNames.Contains(FeatureAttribute.Workspace)) { WaitForProjectSystem(timeout); } GetWaitingService().WaitForAllAsyncOperations(_visualStudioWorkspace, timeout, featureNames); } public void WaitForAllAsyncOperationsOrFail(TimeSpan timeout, params string[] featureNames) { try { WaitForAllAsyncOperations(timeout, featureNames); } catch (Exception e) { var listenerProvider = GetComponentModel().DefaultExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(); var messageBuilder = new StringBuilder("Failed to clean up listeners in a timely manner."); foreach (var token in ((AsynchronousOperationListenerProvider)listenerProvider).GetTokens()) { messageBuilder.AppendLine().Append($" {token}"); } Environment.FailFast("Terminating test process due to unrecoverable timeout.", new TimeoutException(messageBuilder.ToString(), e)); } } private static void WaitForProjectSystem(TimeSpan timeout) { var operationProgressStatus = InvokeOnUIThread(_ => GetGlobalService<SVsOperationProgress, IVsOperationProgressStatusService>()); var stageStatus = operationProgressStatus.GetStageStatus(CommonOperationProgressStageIds.Intellisense); stageStatus.WaitForCompletionAsync().Wait(timeout); } private static void LoadRoslynPackage() { var roslynPackageGuid = RoslynPackageId; var vsShell = GetGlobalService<SVsShell, IVsShell>(); var hresult = vsShell.LoadPackage(ref roslynPackageGuid, out _); Marshal.ThrowExceptionForHR(hresult); } public void CleanUpWorkspace() => InvokeOnUIThread(cancellationToken => { LoadRoslynPackage(); _visualStudioWorkspace.TestHookPartialSolutionsDisabled = true; }); /// <summary> /// Reset options that are manipulated by integration tests back to their default values. /// </summary> public void ResetOptions() { ResetOption(CompletionOptions.EnableArgumentCompletionSnippets); return; // Local function void ResetOption(IOption option) { if (option is IPerLanguageOption) { SetOption(new OptionKey(option, LanguageNames.CSharp), option.DefaultValue); SetOption(new OptionKey(option, LanguageNames.VisualBasic), option.DefaultValue); } else { SetOption(new OptionKey(option), option.DefaultValue); } } } public void CleanUpWaitingService() => InvokeOnUIThread(cancellationToken => { var provider = GetComponentModel().DefaultExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(); if (provider == null) { throw new InvalidOperationException("The test waiting service could not be located."); } GetWaitingService().EnableActiveTokenTracking(true); }); public void SetFeatureOption(string feature, string optionName, string language, string? valueString) => InvokeOnUIThread(cancellationToken => { var option = GetOption(optionName, feature); var value = TypeDescriptor.GetConverter(option.Type).ConvertFromString(valueString); var optionKey = string.IsNullOrWhiteSpace(language) ? new OptionKey(option) : new OptionKey(option, language); SetOption(optionKey, value); }); public string? GetWorkingFolder() { var service = _visualStudioWorkspace.Services.GetRequiredService<IPersistentStorageLocationService>(); return service.TryGetStorageLocation(_visualStudioWorkspace.CurrentSolution); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.SingleTC.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; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SingleTC : FloatingTC<float>, INumericTC<float> { float INumericTC<float>.MinValue => float.NegativeInfinity; float INumericTC<float>.MaxValue => float.PositiveInfinity; float FloatingTC<float>.NaN => float.NaN; float INumericTC<float>.Zero => 0; /// <summary> /// The implementation of Next depends critically on the internal representation of an IEEE floating-point /// number. Every bit sequence between the representation of 0 and MaxValue represents a distinct /// value, and the integer representations are ordered by value the same as the floating-point numbers they represent. /// </summary> public float Next(float value) { Debug.Assert(!float.IsNaN(value)); Debug.Assert(value != float.PositiveInfinity); if (value == 0) return float.Epsilon; if (value < 0) { if (value == -float.Epsilon) return 0.0f; // skip negative zero if (value == float.NegativeInfinity) return float.MinValue; return -UintAsFloat(FloatAsUint(-value) - 1); } if (value == float.MaxValue) return float.PositiveInfinity; return UintAsFloat(FloatAsUint(value) + 1); } private static unsafe uint FloatAsUint(float d) { if (d == 0) return 0; float* dp = &d; uint* lp = (uint*)dp; return *lp; } private static unsafe float UintAsFloat(uint l) { uint* lp = &l; float* dp = (float*)lp; return *dp; } bool INumericTC<float>.Related(BinaryOperatorKind relation, float left, float right) { switch (relation) { case Equal: return left == right || float.IsNaN(left) && float.IsNaN(right); // for our purposes, NaNs are equal case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } float INumericTC<float>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? 0.0F : constantValue.SingleValue; ConstantValue INumericTC<float>.ToConstantValue(float value) => ConstantValue.Create(value); /// <summary> /// Produce a string for testing purposes that is likely to be the same independent of platform and locale. /// </summary> string INumericTC<float>.ToString(float value) => float.IsNaN(value) ? "NaN" : value == float.NegativeInfinity ? "-Inf" : value == float.PositiveInfinity ? "Inf" : FormattableString.Invariant($"{value:G9}"); float INumericTC<float>.Prev(float value) { return -Next(-value); } float INumericTC<float>.Random(Random random) { return (float)(random.NextDouble() * 100 - 50); } } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SingleTC : FloatingTC<float>, INumericTC<float> { float INumericTC<float>.MinValue => float.NegativeInfinity; float INumericTC<float>.MaxValue => float.PositiveInfinity; float FloatingTC<float>.NaN => float.NaN; float INumericTC<float>.Zero => 0; /// <summary> /// The implementation of Next depends critically on the internal representation of an IEEE floating-point /// number. Every bit sequence between the representation of 0 and MaxValue represents a distinct /// value, and the integer representations are ordered by value the same as the floating-point numbers they represent. /// </summary> public float Next(float value) { Debug.Assert(!float.IsNaN(value)); Debug.Assert(value != float.PositiveInfinity); if (value == 0) return float.Epsilon; if (value < 0) { if (value == -float.Epsilon) return 0.0f; // skip negative zero if (value == float.NegativeInfinity) return float.MinValue; return -UintAsFloat(FloatAsUint(-value) - 1); } if (value == float.MaxValue) return float.PositiveInfinity; return UintAsFloat(FloatAsUint(value) + 1); } private static unsafe uint FloatAsUint(float d) { if (d == 0) return 0; float* dp = &d; uint* lp = (uint*)dp; return *lp; } private static unsafe float UintAsFloat(uint l) { uint* lp = &l; float* dp = (float*)lp; return *dp; } bool INumericTC<float>.Related(BinaryOperatorKind relation, float left, float right) { switch (relation) { case Equal: return left == right || float.IsNaN(left) && float.IsNaN(right); // for our purposes, NaNs are equal case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } float INumericTC<float>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? 0.0F : constantValue.SingleValue; ConstantValue INumericTC<float>.ToConstantValue(float value) => ConstantValue.Create(value); /// <summary> /// Produce a string for testing purposes that is likely to be the same independent of platform and locale. /// </summary> string INumericTC<float>.ToString(float value) => float.IsNaN(value) ? "NaN" : value == float.NegativeInfinity ? "-Inf" : value == float.PositiveInfinity ? "Inf" : FormattableString.Invariant($"{value:G9}"); float INumericTC<float>.Prev(float value) { return -Next(-value); } float INumericTC<float>.Random(Random random) { return (float)(random.NextDouble() * 100 - 50); } } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Composition; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Manages remote workspaces. Currently supports only a single, primary workspace of kind <see cref="WorkspaceKind.RemoteWorkspace"/>. /// In future it should support workspaces of all kinds. /// </summary> internal class RemoteWorkspaceManager { /// <summary> /// Default workspace manager used by the product. Tests may specify a custom <see cref="RemoteWorkspaceManager"/> /// in order to override workspace services. /// </summary> internal static readonly RemoteWorkspaceManager Default = new RemoteWorkspaceManager( new SolutionAssetCache(cleanupInterval: TimeSpan.FromMinutes(1), purgeAfter: TimeSpan.FromMinutes(3), gcAfter: TimeSpan.FromMinutes(5))); internal static readonly ImmutableArray<Assembly> RemoteHostAssemblies = MefHostServices.DefaultAssemblies .Add(typeof(ServiceBase).Assembly) .Add(typeof(RemoteWorkspacesResources).Assembly); private readonly Lazy<RemoteWorkspace> _lazyPrimaryWorkspace; internal readonly SolutionAssetCache SolutionAssetCache; // TODO: remove private IAssetSource? _solutionAssetSource; public RemoteWorkspaceManager(SolutionAssetCache assetCache) { _lazyPrimaryWorkspace = new Lazy<RemoteWorkspace>(CreatePrimaryWorkspace); SolutionAssetCache = assetCache; } // TODO: remove [Obsolete("Supports non-brokered services")] internal IAssetSource GetAssetSource() { Contract.ThrowIfNull(_solutionAssetSource, "Storage not initialized"); return _solutionAssetSource; } // TODO: remove [Obsolete("Supports non-brokered services")] internal void InitializeAssetSource(IAssetSource assetSource) { Contract.ThrowIfFalse(_solutionAssetSource == null); _solutionAssetSource = assetSource; } [Obsolete("To be removed: https://github.com/dotnet/roslyn/issues/43477")] public IAssetSource? TryGetAssetSource() => _solutionAssetSource; private static ComposableCatalog CreateCatalog(ImmutableArray<Assembly> assemblies) { var resolver = new Resolver(SimpleAssemblyLoader.Instance); var discovery = new AttributedPartDiscovery(resolver, isNonPublicSupported: true); var parts = Task.Run(async () => await discovery.CreatePartsAsync(assemblies).ConfigureAwait(false)).GetAwaiter().GetResult(); return ComposableCatalog.Create(resolver).AddParts(parts); } private static IExportProviderFactory CreateExportProviderFactory(ComposableCatalog catalog) { var configuration = CompositionConfiguration.Create(catalog); var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration); return runtimeComposition.CreateExportProviderFactory(); } private static RemoteWorkspace CreatePrimaryWorkspace() { var catalog = CreateCatalog(RemoteHostAssemblies); var exportProviderFactory = CreateExportProviderFactory(catalog); var exportProvider = exportProviderFactory.CreateExportProvider(); return new RemoteWorkspace(VisualStudioMefHostServices.Create(exportProvider), WorkspaceKind.RemoteWorkspace); } public virtual RemoteWorkspace GetWorkspace() => _lazyPrimaryWorkspace.Value; public ValueTask<Solution> GetSolutionAsync(ServiceBrokerClient client, PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { var assetSource = new SolutionAssetSource(client); var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, SolutionAssetCache, assetSource); return workspace.GetSolutionAsync(assetProvider, solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, cancellationToken); } private sealed class SimpleAssemblyLoader : IAssemblyLoader { public static readonly IAssemblyLoader Instance = new SimpleAssemblyLoader(); public Assembly LoadAssembly(AssemblyName assemblyName) => Assembly.Load(assemblyName); public Assembly LoadAssembly(string assemblyFullName, string codeBasePath) { var assemblyName = new AssemblyName(assemblyFullName); if (!string.IsNullOrEmpty(codeBasePath)) { assemblyName.CodeBase = codeBasePath; } return LoadAssembly(assemblyName); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Composition; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Manages remote workspaces. Currently supports only a single, primary workspace of kind <see cref="WorkspaceKind.RemoteWorkspace"/>. /// In future it should support workspaces of all kinds. /// </summary> internal class RemoteWorkspaceManager { /// <summary> /// Default workspace manager used by the product. Tests may specify a custom <see cref="RemoteWorkspaceManager"/> /// in order to override workspace services. /// </summary> internal static readonly RemoteWorkspaceManager Default = new RemoteWorkspaceManager( new SolutionAssetCache(cleanupInterval: TimeSpan.FromMinutes(1), purgeAfter: TimeSpan.FromMinutes(3), gcAfter: TimeSpan.FromMinutes(5))); internal static readonly ImmutableArray<Assembly> RemoteHostAssemblies = MefHostServices.DefaultAssemblies .Add(typeof(ServiceBase).Assembly) .Add(typeof(RemoteWorkspacesResources).Assembly); private readonly Lazy<RemoteWorkspace> _lazyPrimaryWorkspace; internal readonly SolutionAssetCache SolutionAssetCache; // TODO: remove private IAssetSource? _solutionAssetSource; public RemoteWorkspaceManager(SolutionAssetCache assetCache) { _lazyPrimaryWorkspace = new Lazy<RemoteWorkspace>(CreatePrimaryWorkspace); SolutionAssetCache = assetCache; } // TODO: remove [Obsolete("Supports non-brokered services")] internal IAssetSource GetAssetSource() { Contract.ThrowIfNull(_solutionAssetSource, "Storage not initialized"); return _solutionAssetSource; } // TODO: remove [Obsolete("Supports non-brokered services")] internal void InitializeAssetSource(IAssetSource assetSource) { Contract.ThrowIfFalse(_solutionAssetSource == null); _solutionAssetSource = assetSource; } [Obsolete("To be removed: https://github.com/dotnet/roslyn/issues/43477")] public IAssetSource? TryGetAssetSource() => _solutionAssetSource; private static ComposableCatalog CreateCatalog(ImmutableArray<Assembly> assemblies) { var resolver = new Resolver(SimpleAssemblyLoader.Instance); var discovery = new AttributedPartDiscovery(resolver, isNonPublicSupported: true); var parts = Task.Run(async () => await discovery.CreatePartsAsync(assemblies).ConfigureAwait(false)).GetAwaiter().GetResult(); return ComposableCatalog.Create(resolver).AddParts(parts); } private static IExportProviderFactory CreateExportProviderFactory(ComposableCatalog catalog) { var configuration = CompositionConfiguration.Create(catalog); var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration); return runtimeComposition.CreateExportProviderFactory(); } private static RemoteWorkspace CreatePrimaryWorkspace() { var catalog = CreateCatalog(RemoteHostAssemblies); var exportProviderFactory = CreateExportProviderFactory(catalog); var exportProvider = exportProviderFactory.CreateExportProvider(); return new RemoteWorkspace(VisualStudioMefHostServices.Create(exportProvider), WorkspaceKind.RemoteWorkspace); } public virtual RemoteWorkspace GetWorkspace() => _lazyPrimaryWorkspace.Value; public ValueTask<Solution> GetSolutionAsync(ServiceBrokerClient client, PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { var assetSource = new SolutionAssetSource(client); var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, SolutionAssetCache, assetSource); return workspace.GetSolutionAsync(assetProvider, solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, cancellationToken); } private sealed class SimpleAssemblyLoader : IAssemblyLoader { public static readonly IAssemblyLoader Instance = new SimpleAssemblyLoader(); public Assembly LoadAssembly(AssemblyName assemblyName) => Assembly.Load(assemblyName); public Assembly LoadAssembly(string assemblyFullName, string codeBasePath) { var assemblyName = new AssemblyName(assemblyFullName); if (!string.IsNullOrEmpty(codeBasePath)) { assemblyName.CodeBase = codeBasePath; } return LoadAssembly(assemblyName); } } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Portable/Errors/LazyDiagnosticInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class LazyDiagnosticInfo : DiagnosticInfo { private DiagnosticInfo? _lazyInfo; protected LazyDiagnosticInfo() : base(CSharp.MessageProvider.Instance, (int)ErrorCode.Unknown) { } internal sealed override DiagnosticInfo GetResolvedInfo() { if (_lazyInfo == null) { Interlocked.CompareExchange(ref _lazyInfo, ResolveInfo() ?? CSDiagnosticInfo.VoidDiagnosticInfo, null); } return _lazyInfo; } protected abstract DiagnosticInfo? ResolveInfo(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class LazyDiagnosticInfo : DiagnosticInfo { private DiagnosticInfo? _lazyInfo; protected LazyDiagnosticInfo() : base(CSharp.MessageProvider.Instance, (int)ErrorCode.Unknown) { } internal sealed override DiagnosticInfo GetResolvedInfo() { if (_lazyInfo == null) { Interlocked.CompareExchange(ref _lazyInfo, ResolveInfo() ?? CSDiagnosticInfo.VoidDiagnosticInfo, null); } return _lazyInfo; } protected abstract DiagnosticInfo? ResolveInfo(); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicBuild.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; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicBuild : AbstractIntegrationTest { public BasicBuild(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.SolutionExplorer.CreateSolution(nameof(BasicBuild)); var testProj = new ProjectUtils.Project("TestProj"); VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ConsoleApplication, LanguageNames.VisualBasic); } [WpfFact, Trait(Traits.Feature, Traits.Features.Build)] public void BuildProject() { var editorText = @"Module Program Sub Main() Console.WriteLine(""Hello, World!"") End Sub End Module"; VisualStudio.Editor.SetText(editorText); // TODO: Validate build works as expected } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicBuild : AbstractIntegrationTest { public BasicBuild(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.SolutionExplorer.CreateSolution(nameof(BasicBuild)); var testProj = new ProjectUtils.Project("TestProj"); VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ConsoleApplication, LanguageNames.VisualBasic); } [WpfFact, Trait(Traits.Feature, Traits.Features.Build)] public void BuildProject() { var editorText = @"Module Program Sub Main() Console.WriteLine(""Hello, World!"") End Sub End Module"; VisualStudio.Editor.SetText(editorText); // TODO: Validate build works as expected } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.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.Concurrent; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MakeFieldReadonly { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal sealed class MakeFieldReadonlyDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public MakeFieldReadonlyDiagnosticAnalyzer() : base( IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId, EnforceOnBuildValues.MakeFieldReadonly, CodeStyleOptions2.PreferReadonly, new LocalizableResourceString(nameof(AnalyzersResources.Add_readonly_modifier), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Make_field_readonly), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; // We need to analyze generated code to get callbacks for read/writes to non-generated members in generated code. protected override bool ReceiveAnalysisCallbacksForGeneratedCode => true; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(compilationStartContext => { // State map for fields: // 'isCandidate' : Indicates whether the field is a candidate to be made readonly based on it's options. // 'written' : Indicates if there are any writes to the field outside the constructor and field initializer. var fieldStateMap = new ConcurrentDictionary<IFieldSymbol, (bool isCandidate, bool written)>(); var threadStaticAttribute = compilationStartContext.Compilation.ThreadStaticAttributeType(); // We register following actions in the compilation: // 1. A symbol action for field symbols to ensure the field state is initialized for every field in // the compilation. // 2. An operation action for field references to detect if a candidate field is written outside // constructor and field initializer, and update field state accordingly. // 3. A symbol start/end action for named types to report diagnostics for candidate fields that were // not written outside constructor and field initializer. compilationStartContext.RegisterSymbolAction(AnalyzeFieldSymbol, SymbolKind.Field); compilationStartContext.RegisterSymbolStartAction(symbolStartContext => { symbolStartContext.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference); symbolStartContext.RegisterSymbolEndAction(OnSymbolEnd); }, SymbolKind.NamedType); return; // Local functions. void AnalyzeFieldSymbol(SymbolAnalysisContext symbolContext) { _ = TryGetOrInitializeFieldState((IFieldSymbol)symbolContext.Symbol, symbolContext.Options, symbolContext.CancellationToken); } void AnalyzeOperation(OperationAnalysisContext operationContext) { var fieldReference = (IFieldReferenceOperation)operationContext.Operation; var (isCandidate, written) = TryGetOrInitializeFieldState(fieldReference.Field, operationContext.Options, operationContext.CancellationToken); // Ignore fields that are not candidates or have already been written outside the constructor/field initializer. if (!isCandidate || written) { return; } // Check if this is a field write outside constructor and field initializer, and update field state accordingly. if (IsFieldWrite(fieldReference, operationContext.ContainingSymbol)) { UpdateFieldStateOnWrite(fieldReference.Field); } } void OnSymbolEnd(SymbolAnalysisContext symbolEndContext) { // Report diagnostics for candidate fields that are not written outside constructor and field initializer. var members = ((INamedTypeSymbol)symbolEndContext.Symbol).GetMembers(); foreach (var member in members) { if (member is IFieldSymbol field && fieldStateMap.TryRemove(field, out var value)) { var (isCandidate, written) = value; if (isCandidate && !written) { var option = GetCodeStyleOption(field, symbolEndContext.Options, symbolEndContext.CancellationToken); var diagnostic = DiagnosticHelper.Create( Descriptor, field.Locations[0], option.Notification.Severity, additionalLocations: null, properties: null); symbolEndContext.ReportDiagnostic(diagnostic); } } } } static bool IsCandidateField(IFieldSymbol symbol, INamedTypeSymbol threadStaticAttribute) => symbol.DeclaredAccessibility == Accessibility.Private && !symbol.IsReadOnly && !symbol.IsConst && !symbol.IsImplicitlyDeclared && symbol.Locations.Length == 1 && symbol.Type.IsMutableValueType() == false && !symbol.IsFixedSizeBuffer && !symbol.GetAttributes().Any( static (a, threadStaticAttribute) => SymbolEqualityComparer.Default.Equals(a.AttributeClass, threadStaticAttribute), threadStaticAttribute); // Method to update the field state for a candidate field written outside constructor and field initializer. void UpdateFieldStateOnWrite(IFieldSymbol field) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); Debug.Assert(fieldStateMap.ContainsKey(field)); fieldStateMap[field] = (isCandidate: true, written: true); } // Method to get or initialize the field state. (bool isCandidate, bool written) TryGetOrInitializeFieldState(IFieldSymbol fieldSymbol, AnalyzerOptions options, CancellationToken cancellationToken) { if (!IsCandidateField(fieldSymbol, threadStaticAttribute)) { return default; } if (fieldStateMap.TryGetValue(fieldSymbol, out var result)) { return result; } result = ComputeInitialFieldState(fieldSymbol, options, threadStaticAttribute, cancellationToken); return fieldStateMap.GetOrAdd(fieldSymbol, result); } // Method to compute the initial field state. static (bool isCandidate, bool written) ComputeInitialFieldState(IFieldSymbol field, AnalyzerOptions options, INamedTypeSymbol threadStaticAttribute, CancellationToken cancellationToken) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); var option = GetCodeStyleOption(field, options, cancellationToken); if (option == null || !option.Value) { return default; } return (isCandidate: true, written: false); } }); } private static bool IsFieldWrite(IFieldReferenceOperation fieldReference, ISymbol owningSymbol) { // Check if the underlying member is being written or a writable reference to the member is taken. var valueUsageInfo = fieldReference.GetValueUsageInfo(owningSymbol); if (!valueUsageInfo.IsWrittenTo()) { return false; } // Writes to fields inside constructor are ignored, except for the below cases: // 1. Instance reference of an instance field being written is not the instance being initialized by the constructor. // 2. Field is being written inside a lambda or local function. // Check if we are in the constructor of the containing type of the written field. var isInConstructor = owningSymbol.IsConstructor(); var isInStaticConstructor = owningSymbol.IsStaticConstructor(); var field = fieldReference.Field; if ((isInConstructor || isInStaticConstructor) && field.ContainingType == owningSymbol.ContainingType) { // For instance fields, ensure that the instance reference is being initialized by the constructor. var instanceFieldWrittenInCtor = isInConstructor && fieldReference.Instance?.Kind == OperationKind.InstanceReference && !fieldReference.IsTargetOfObjectMemberInitializer(); // For static fields, ensure that we are in the static constructor. var staticFieldWrittenInStaticCtor = isInStaticConstructor && field.IsStatic; if (instanceFieldWrittenInCtor || staticFieldWrittenInStaticCtor) { // Finally, ensure that the write is not inside a lambda or local function. if (fieldReference.TryGetContainingAnonymousFunctionOrLocalFunction() is null) { // It is safe to ignore this write. return false; } } } return true; } private static CodeStyleOption2<bool> GetCodeStyleOption(IFieldSymbol field, AnalyzerOptions options, CancellationToken cancellationToken) => options.GetOption(CodeStyleOptions2.PreferReadonly, field.Language, field.Locations[0].SourceTree, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Concurrent; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MakeFieldReadonly { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal sealed class MakeFieldReadonlyDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public MakeFieldReadonlyDiagnosticAnalyzer() : base( IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId, EnforceOnBuildValues.MakeFieldReadonly, CodeStyleOptions2.PreferReadonly, new LocalizableResourceString(nameof(AnalyzersResources.Add_readonly_modifier), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Make_field_readonly), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; // We need to analyze generated code to get callbacks for read/writes to non-generated members in generated code. protected override bool ReceiveAnalysisCallbacksForGeneratedCode => true; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(compilationStartContext => { // State map for fields: // 'isCandidate' : Indicates whether the field is a candidate to be made readonly based on it's options. // 'written' : Indicates if there are any writes to the field outside the constructor and field initializer. var fieldStateMap = new ConcurrentDictionary<IFieldSymbol, (bool isCandidate, bool written)>(); var threadStaticAttribute = compilationStartContext.Compilation.ThreadStaticAttributeType(); // We register following actions in the compilation: // 1. A symbol action for field symbols to ensure the field state is initialized for every field in // the compilation. // 2. An operation action for field references to detect if a candidate field is written outside // constructor and field initializer, and update field state accordingly. // 3. A symbol start/end action for named types to report diagnostics for candidate fields that were // not written outside constructor and field initializer. compilationStartContext.RegisterSymbolAction(AnalyzeFieldSymbol, SymbolKind.Field); compilationStartContext.RegisterSymbolStartAction(symbolStartContext => { symbolStartContext.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference); symbolStartContext.RegisterSymbolEndAction(OnSymbolEnd); }, SymbolKind.NamedType); return; // Local functions. void AnalyzeFieldSymbol(SymbolAnalysisContext symbolContext) { _ = TryGetOrInitializeFieldState((IFieldSymbol)symbolContext.Symbol, symbolContext.Options, symbolContext.CancellationToken); } void AnalyzeOperation(OperationAnalysisContext operationContext) { var fieldReference = (IFieldReferenceOperation)operationContext.Operation; var (isCandidate, written) = TryGetOrInitializeFieldState(fieldReference.Field, operationContext.Options, operationContext.CancellationToken); // Ignore fields that are not candidates or have already been written outside the constructor/field initializer. if (!isCandidate || written) { return; } // Check if this is a field write outside constructor and field initializer, and update field state accordingly. if (IsFieldWrite(fieldReference, operationContext.ContainingSymbol)) { UpdateFieldStateOnWrite(fieldReference.Field); } } void OnSymbolEnd(SymbolAnalysisContext symbolEndContext) { // Report diagnostics for candidate fields that are not written outside constructor and field initializer. var members = ((INamedTypeSymbol)symbolEndContext.Symbol).GetMembers(); foreach (var member in members) { if (member is IFieldSymbol field && fieldStateMap.TryRemove(field, out var value)) { var (isCandidate, written) = value; if (isCandidate && !written) { var option = GetCodeStyleOption(field, symbolEndContext.Options, symbolEndContext.CancellationToken); var diagnostic = DiagnosticHelper.Create( Descriptor, field.Locations[0], option.Notification.Severity, additionalLocations: null, properties: null); symbolEndContext.ReportDiagnostic(diagnostic); } } } } static bool IsCandidateField(IFieldSymbol symbol, INamedTypeSymbol threadStaticAttribute) => symbol.DeclaredAccessibility == Accessibility.Private && !symbol.IsReadOnly && !symbol.IsConst && !symbol.IsImplicitlyDeclared && symbol.Locations.Length == 1 && symbol.Type.IsMutableValueType() == false && !symbol.IsFixedSizeBuffer && !symbol.GetAttributes().Any( static (a, threadStaticAttribute) => SymbolEqualityComparer.Default.Equals(a.AttributeClass, threadStaticAttribute), threadStaticAttribute); // Method to update the field state for a candidate field written outside constructor and field initializer. void UpdateFieldStateOnWrite(IFieldSymbol field) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); Debug.Assert(fieldStateMap.ContainsKey(field)); fieldStateMap[field] = (isCandidate: true, written: true); } // Method to get or initialize the field state. (bool isCandidate, bool written) TryGetOrInitializeFieldState(IFieldSymbol fieldSymbol, AnalyzerOptions options, CancellationToken cancellationToken) { if (!IsCandidateField(fieldSymbol, threadStaticAttribute)) { return default; } if (fieldStateMap.TryGetValue(fieldSymbol, out var result)) { return result; } result = ComputeInitialFieldState(fieldSymbol, options, threadStaticAttribute, cancellationToken); return fieldStateMap.GetOrAdd(fieldSymbol, result); } // Method to compute the initial field state. static (bool isCandidate, bool written) ComputeInitialFieldState(IFieldSymbol field, AnalyzerOptions options, INamedTypeSymbol threadStaticAttribute, CancellationToken cancellationToken) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); var option = GetCodeStyleOption(field, options, cancellationToken); if (option == null || !option.Value) { return default; } return (isCandidate: true, written: false); } }); } private static bool IsFieldWrite(IFieldReferenceOperation fieldReference, ISymbol owningSymbol) { // Check if the underlying member is being written or a writable reference to the member is taken. var valueUsageInfo = fieldReference.GetValueUsageInfo(owningSymbol); if (!valueUsageInfo.IsWrittenTo()) { return false; } // Writes to fields inside constructor are ignored, except for the below cases: // 1. Instance reference of an instance field being written is not the instance being initialized by the constructor. // 2. Field is being written inside a lambda or local function. // Check if we are in the constructor of the containing type of the written field. var isInConstructor = owningSymbol.IsConstructor(); var isInStaticConstructor = owningSymbol.IsStaticConstructor(); var field = fieldReference.Field; if ((isInConstructor || isInStaticConstructor) && field.ContainingType == owningSymbol.ContainingType) { // For instance fields, ensure that the instance reference is being initialized by the constructor. var instanceFieldWrittenInCtor = isInConstructor && fieldReference.Instance?.Kind == OperationKind.InstanceReference && !fieldReference.IsTargetOfObjectMemberInitializer(); // For static fields, ensure that we are in the static constructor. var staticFieldWrittenInStaticCtor = isInStaticConstructor && field.IsStatic; if (instanceFieldWrittenInCtor || staticFieldWrittenInStaticCtor) { // Finally, ensure that the write is not inside a lambda or local function. if (fieldReference.TryGetContainingAnonymousFunctionOrLocalFunction() is null) { // It is safe to ignore this write. return false; } } } return true; } private static CodeStyleOption2<bool> GetCodeStyleOption(IFieldSymbol field, AnalyzerOptions options, CancellationToken cancellationToken) => options.GetOption(CodeStyleOptions2.PreferReadonly, field.Language, field.Locations[0].SourceTree, cancellationToken); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/Core/Portable/SignatureHelp/ISignatureHelpProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.SignatureHelp { internal interface ISignatureHelpProvider { /// <summary> /// Returns true if the character might trigger completion, /// e.g. '(' and ',' for method invocations /// </summary> bool IsTriggerCharacter(char ch); /// <summary> /// Returns true if the character might end a Signature Help session, /// e.g. ')' for method invocations. /// </summary> bool IsRetriggerCharacter(char ch); /// <summary> /// Returns valid signature help items at the specified position in the document. /// </summary> Task<SignatureHelpItems?> GetItemsAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.SignatureHelp { internal interface ISignatureHelpProvider { /// <summary> /// Returns true if the character might trigger completion, /// e.g. '(' and ',' for method invocations /// </summary> bool IsTriggerCharacter(char ch); /// <summary> /// Returns true if the character might end a Signature Help session, /// e.g. ')' for method invocations. /// </summary> bool IsRetriggerCharacter(char ch); /// <summary> /// Returns valid signature help items at the specified position in the document. /// </summary> Task<SignatureHelpItems?> GetItemsAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/Core/EditorConfigSettings/Updater/SettingsUpdateHelper.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.Text.RegularExpressions; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater { internal static partial class SettingsUpdateHelper { private const string DiagnosticOptionPrefix = "dotnet_diagnostic."; private const string SeveritySuffix = ".severity"; public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, IReadOnlyList<(AnalyzerSetting option, DiagnosticSeverity value)> settingsToUpdate) { if (originalText is null) return null; if (settingsToUpdate is null) return null; if (filePath is null) return null; var settings = settingsToUpdate.Select(x => TryGetOptionValueAndLanguage(x.option, x.value)).ToList(); return TryUpdateAnalyzerConfigDocument(originalText, filePath, settings); static (string option, string value, Language language) TryGetOptionValueAndLanguage(AnalyzerSetting diagnostic, DiagnosticSeverity severity) { var optionName = $"{DiagnosticOptionPrefix}{diagnostic.Id}{SeveritySuffix}"; var optionValue = severity.ToEditorConfigString(); var language = diagnostic.Language; return (optionName, optionValue, language); } } public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, OptionSet optionSet, IReadOnlyList<(IOption2 option, object value)> settingsToUpdate) { if (originalText is null) return null; if (settingsToUpdate is null) return null; if (filePath is null) return null; var updatedText = originalText; var settings = settingsToUpdate.Select(x => TryGetOptionValueAndLanguage(x.option, x.value, optionSet)) .Where(x => x.success) .Select(x => (x.option, x.value, x.language)) .ToList(); return TryUpdateAnalyzerConfigDocument(originalText, filePath, settings); static (bool success, string option, string value, Language language) TryGetOptionValueAndLanguage(IOption2 option, object value, OptionSet optionSet) { if (option.StorageLocations.FirstOrDefault(x => x is IEditorConfigStorageLocation2) is not IEditorConfigStorageLocation2 storageLocation) { return (false, null!, null!, default); } var optionName = storageLocation.KeyName; var optionValue = storageLocation.GetEditorConfigStringValue(value, optionSet); if (value is ICodeStyleOption codeStyleOption && !optionValue.Contains(':')) { var severity = codeStyleOption.Notification switch { { Severity: ReportDiagnostic.Hidden } => "silent", { Severity: ReportDiagnostic.Info } => "suggestion", { Severity: ReportDiagnostic.Warn } => "warning", { Severity: ReportDiagnostic.Error } => "error", _ => string.Empty }; optionValue = $"{optionValue}:{severity}"; } var language = option.IsPerLanguage ? Language.CSharp | Language.VisualBasic : Language.CSharp; return (true, optionName, optionValue, language); } } public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, IReadOnlyList<(string option, string value, Language language)> settingsToUpdate) { if (originalText is null) throw new ArgumentNullException(nameof(originalText)); if (filePath is null) throw new ArgumentNullException(nameof(filePath)); if (settingsToUpdate is null) throw new ArgumentNullException(nameof(settingsToUpdate)); var updatedText = originalText; TextLine? lastValidHeaderSpanEnd; TextLine? lastValidSpecificHeaderSpanEnd; foreach (var (option, value, language) in settingsToUpdate) { SourceText? newText; (newText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd) = UpdateIfExistsInFile(updatedText, filePath, option, value, language); if (newText != null) { updatedText = newText; continue; } (newText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd) = AddMissingRule(updatedText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd, option, value, language); if (newText != null) { updatedText = newText; } } return updatedText.Equals(originalText) ? null : updatedText; } /// <summary> /// <para>Regular expression for .editorconfig header.</para> /// <para>For example: "[*.cs] # Optional comment"</para> /// <para> "[*.{vb,cs}]"</para> /// <para> "[*] ; Optional comment"</para> /// <para> "[ConsoleApp/Program.cs]"</para> /// </summary> private static readonly Regex s_headerPattern = new(@"\[(\*|[^ #;\[\]]+\.({[^ #;{}\.\[\]]+}|[^ #;{}\.\[\]]+))\]\s*([#;].*)?"); /// <summary> /// <para>Regular expression for .editorconfig code style option entry.</para> /// <para>For example:</para> /// <para> 1. "dotnet_style_object_initializer = true # Optional comment"</para> /// <para> 2. "dotnet_style_object_initializer = true:suggestion ; Optional comment"</para> /// <para> 3. "dotnet_diagnostic.CA2000.severity = suggestion # Optional comment"</para> /// <para> 4. "dotnet_analyzer_diagnostic.category-Security.severity = suggestion # Optional comment"</para> /// <para> 5. "dotnet_analyzer_diagnostic.severity = suggestion # Optional comment"</para> /// <para>Regex groups:</para> /// <para> 1. Option key</para> /// <para> 2. Option value</para> /// <para> 3. Optional severity suffix in option value, i.e. ':severity' suffix</para> /// <para>4. Optional comment suffix</para> /// </summary> private static readonly Regex s_optionEntryPattern = new($@"(.*)=([\w, ]*)(:[\w]+)?([ ]*[;#].*)?"); private static (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) UpdateIfExistsInFile(SourceText editorConfigText, string filePath, string optionName, string optionValue, Language language) { var editorConfigDirectory = PathUtilities.GetDirectoryName(filePath); Assumes.NotNull(editorConfigDirectory); var relativePath = PathUtilities.GetRelativePath(editorConfigDirectory.ToLowerInvariant(), filePath); TextLine? mostRecentHeader = null; TextLine? lastValidHeader = null; TextLine? lastValidHeaderSpanEnd = null; TextLine? lastValidSpecificHeader = null; TextLine? lastValidSpecificHeaderSpanEnd = null; var textChange = new TextChange(); foreach (var curLine in editorConfigText.Lines) { var curLineText = curLine.ToString(); if (s_optionEntryPattern.IsMatch(curLineText)) { var groups = s_optionEntryPattern.Match(curLineText).Groups; var (untrimmedKey, key, value, severity, comment) = GetGroups(groups); // Verify the most recent header is a valid header if (IsValidHeader(mostRecentHeader, lastValidHeader) && string.Equals(key, optionName, StringComparison.OrdinalIgnoreCase)) { // We found the rule in the file -- replace it with updated option value. textChange = new TextChange(curLine.Span, $"{untrimmedKey}={optionValue}{comment}"); } } else if (s_headerPattern.IsMatch(curLineText.Trim())) { mostRecentHeader = curLine; if (ShouldSetAsLastValidHeader(curLineText, out var mostRecentHeaderText)) { lastValidHeader = mostRecentHeader; } else { var (fileName, splicedFileExtensions) = ParseHeaderParts(mostRecentHeaderText); if ((relativePath.IsEmpty() || new Regex(fileName).IsMatch(relativePath)) && HeaderMatchesLanguageRequirements(language, splicedFileExtensions)) { lastValidHeader = mostRecentHeader; } } } // We want to keep track of how far this (valid) section spans. if (IsValidHeader(mostRecentHeader, lastValidHeader) && IsNotEmptyOrComment(curLineText)) { lastValidHeaderSpanEnd = curLine; if (lastValidSpecificHeader != null && mostRecentHeader.Equals(lastValidSpecificHeader)) { lastValidSpecificHeaderSpanEnd = curLine; } } } // We return only the last text change in case of duplicate entries for the same rule. if (textChange != default) { return (editorConfigText.WithChanges(textChange), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } // Rule not found. return (null, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); static (string untrimmedKey, string key, string value, string severitySuffixInValue, string commentValue) GetGroups(GroupCollection groups) { var untrimmedKey = groups[1].Value.ToString(); var key = untrimmedKey.Trim(); var value = groups[2].Value.ToString(); var severitySuffixInValue = groups[3].Value.ToString(); var commentValue = groups[4].Value.ToString(); return (untrimmedKey, key, value, severitySuffixInValue, commentValue); } static bool IsValidHeader(TextLine? mostRecentHeader, TextLine? lastValidHeader) { return mostRecentHeader is not null && lastValidHeader is not null && mostRecentHeader.Equals(lastValidHeader); } static bool ShouldSetAsLastValidHeader(string curLineText, out string mostRecentHeaderText) { var groups = s_headerPattern.Match(curLineText.Trim()).Groups; mostRecentHeaderText = groups[1].Value.ToString().ToLowerInvariant(); return mostRecentHeaderText.Equals("*", StringComparison.Ordinal); } static (string fileName, string[] splicedFileExtensions) ParseHeaderParts(string mostRecentHeaderText) { // We splice on the last occurrence of '.' to account for filenames containing periods. var nameExtensionSplitIndex = mostRecentHeaderText.LastIndexOf('.'); var fileName = mostRecentHeaderText.Substring(0, nameExtensionSplitIndex); var splicedFileExtensions = mostRecentHeaderText[(nameExtensionSplitIndex + 1)..].Split(',', ' ', '{', '}'); // Replacing characters in the header with the regex equivalent. fileName = fileName.Replace(".", @"\."); fileName = fileName.Replace("*", ".*"); fileName = fileName.Replace("/", @"\/"); return (fileName, splicedFileExtensions); } static bool IsNotEmptyOrComment(string currentLineText) { return !string.IsNullOrWhiteSpace(currentLineText) && !currentLineText.Trim().StartsWith("#", StringComparison.OrdinalIgnoreCase); } static bool HeaderMatchesLanguageRequirements(Language language, string[] splicedFileExtensions) { return IsCSharpOnly(language, splicedFileExtensions) || IsVisualBasicOnly(language, splicedFileExtensions) || IsBothVisualBasicAndCSharp(language, splicedFileExtensions); } static bool IsCSharpOnly(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.CSharp) && !language.HasFlag(Language.VisualBasic) && splicedFileExtensions.Contains("cs") && splicedFileExtensions.Length == 1; } static bool IsVisualBasicOnly(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.VisualBasic) && !language.HasFlag(Language.CSharp) && splicedFileExtensions.Contains("vb") && splicedFileExtensions.Length == 1; } static bool IsBothVisualBasicAndCSharp(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.VisualBasic) && language.HasFlag(Language.CSharp) && splicedFileExtensions.Contains("vb") && splicedFileExtensions.Contains("cs"); } } private static (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) AddMissingRule(SourceText editorConfigText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd, string optionName, string optionValue, Language language) { var newEntry = $"{optionName}={optionValue}"; if (lastValidSpecificHeaderSpanEnd.HasValue) { if (lastValidSpecificHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; // TODO(jmarolf): do we need to read in the users newline settings? } return (editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(lastValidSpecificHeaderSpanEnd.Value.Span.End, 0), newEntry)), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } else if (lastValidHeaderSpanEnd.HasValue) { if (lastValidHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; // TODO(jmarolf): do we need to read in the users newline settings? } return (editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(lastValidHeaderSpanEnd.Value.Span.End, 0), newEntry)), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } // We need to generate a new header such as '[*.cs]' or '[*.vb]': // - For compiler diagnostic entries and code style entries which have per-language option = false, generate only [*.cs] or [*.vb]. // - For the remainder, generate [*.{cs,vb}] // Insert a newline if not already present var lines = editorConfigText.Lines; var lastLine = lines.Count > 0 ? lines[^1] : default; var prefix = string.Empty; if (lastLine.ToString().Trim().Length != 0) { prefix = "\r\n"; } // Insert newline if file is not empty if (lines.Count > 1 && lastLine.ToString().Trim().Length == 0) { prefix += "\r\n"; } if (language.HasFlag(Language.CSharp) && language.HasFlag(Language.VisualBasic)) { prefix += "[*.{cs,vb}]\r\n"; } else if (language.HasFlag(Language.CSharp)) { prefix += "[*.cs]\r\n"; } else if (language.HasFlag(Language.VisualBasic)) { prefix += "[*.vb]\r\n"; } var result = editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(editorConfigText.Length, 0), prefix + newEntry)); return (result, lastValidHeaderSpanEnd, result.Lines[^2]); } } }
// Licensed to the .NET Foundation under one or more 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.Text.RegularExpressions; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater { internal static partial class SettingsUpdateHelper { private const string DiagnosticOptionPrefix = "dotnet_diagnostic."; private const string SeveritySuffix = ".severity"; public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, IReadOnlyList<(AnalyzerSetting option, DiagnosticSeverity value)> settingsToUpdate) { if (originalText is null) return null; if (settingsToUpdate is null) return null; if (filePath is null) return null; var settings = settingsToUpdate.Select(x => TryGetOptionValueAndLanguage(x.option, x.value)).ToList(); return TryUpdateAnalyzerConfigDocument(originalText, filePath, settings); static (string option, string value, Language language) TryGetOptionValueAndLanguage(AnalyzerSetting diagnostic, DiagnosticSeverity severity) { var optionName = $"{DiagnosticOptionPrefix}{diagnostic.Id}{SeveritySuffix}"; var optionValue = severity.ToEditorConfigString(); var language = diagnostic.Language; return (optionName, optionValue, language); } } public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, OptionSet optionSet, IReadOnlyList<(IOption2 option, object value)> settingsToUpdate) { if (originalText is null) return null; if (settingsToUpdate is null) return null; if (filePath is null) return null; var updatedText = originalText; var settings = settingsToUpdate.Select(x => TryGetOptionValueAndLanguage(x.option, x.value, optionSet)) .Where(x => x.success) .Select(x => (x.option, x.value, x.language)) .ToList(); return TryUpdateAnalyzerConfigDocument(originalText, filePath, settings); static (bool success, string option, string value, Language language) TryGetOptionValueAndLanguage(IOption2 option, object value, OptionSet optionSet) { if (option.StorageLocations.FirstOrDefault(x => x is IEditorConfigStorageLocation2) is not IEditorConfigStorageLocation2 storageLocation) { return (false, null!, null!, default); } var optionName = storageLocation.KeyName; var optionValue = storageLocation.GetEditorConfigStringValue(value, optionSet); if (value is ICodeStyleOption codeStyleOption && !optionValue.Contains(':')) { var severity = codeStyleOption.Notification switch { { Severity: ReportDiagnostic.Hidden } => "silent", { Severity: ReportDiagnostic.Info } => "suggestion", { Severity: ReportDiagnostic.Warn } => "warning", { Severity: ReportDiagnostic.Error } => "error", _ => string.Empty }; optionValue = $"{optionValue}:{severity}"; } var language = option.IsPerLanguage ? Language.CSharp | Language.VisualBasic : Language.CSharp; return (true, optionName, optionValue, language); } } public static SourceText? TryUpdateAnalyzerConfigDocument(SourceText originalText, string filePath, IReadOnlyList<(string option, string value, Language language)> settingsToUpdate) { if (originalText is null) throw new ArgumentNullException(nameof(originalText)); if (filePath is null) throw new ArgumentNullException(nameof(filePath)); if (settingsToUpdate is null) throw new ArgumentNullException(nameof(settingsToUpdate)); var updatedText = originalText; TextLine? lastValidHeaderSpanEnd; TextLine? lastValidSpecificHeaderSpanEnd; foreach (var (option, value, language) in settingsToUpdate) { SourceText? newText; (newText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd) = UpdateIfExistsInFile(updatedText, filePath, option, value, language); if (newText != null) { updatedText = newText; continue; } (newText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd) = AddMissingRule(updatedText, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd, option, value, language); if (newText != null) { updatedText = newText; } } return updatedText.Equals(originalText) ? null : updatedText; } /// <summary> /// <para>Regular expression for .editorconfig header.</para> /// <para>For example: "[*.cs] # Optional comment"</para> /// <para> "[*.{vb,cs}]"</para> /// <para> "[*] ; Optional comment"</para> /// <para> "[ConsoleApp/Program.cs]"</para> /// </summary> private static readonly Regex s_headerPattern = new(@"\[(\*|[^ #;\[\]]+\.({[^ #;{}\.\[\]]+}|[^ #;{}\.\[\]]+))\]\s*([#;].*)?"); /// <summary> /// <para>Regular expression for .editorconfig code style option entry.</para> /// <para>For example:</para> /// <para> 1. "dotnet_style_object_initializer = true # Optional comment"</para> /// <para> 2. "dotnet_style_object_initializer = true:suggestion ; Optional comment"</para> /// <para> 3. "dotnet_diagnostic.CA2000.severity = suggestion # Optional comment"</para> /// <para> 4. "dotnet_analyzer_diagnostic.category-Security.severity = suggestion # Optional comment"</para> /// <para> 5. "dotnet_analyzer_diagnostic.severity = suggestion # Optional comment"</para> /// <para>Regex groups:</para> /// <para> 1. Option key</para> /// <para> 2. Option value</para> /// <para> 3. Optional severity suffix in option value, i.e. ':severity' suffix</para> /// <para>4. Optional comment suffix</para> /// </summary> private static readonly Regex s_optionEntryPattern = new($@"(.*)=([\w, ]*)(:[\w]+)?([ ]*[;#].*)?"); private static (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) UpdateIfExistsInFile(SourceText editorConfigText, string filePath, string optionName, string optionValue, Language language) { var editorConfigDirectory = PathUtilities.GetDirectoryName(filePath); Assumes.NotNull(editorConfigDirectory); var relativePath = PathUtilities.GetRelativePath(editorConfigDirectory.ToLowerInvariant(), filePath); TextLine? mostRecentHeader = null; TextLine? lastValidHeader = null; TextLine? lastValidHeaderSpanEnd = null; TextLine? lastValidSpecificHeader = null; TextLine? lastValidSpecificHeaderSpanEnd = null; var textChange = new TextChange(); foreach (var curLine in editorConfigText.Lines) { var curLineText = curLine.ToString(); if (s_optionEntryPattern.IsMatch(curLineText)) { var groups = s_optionEntryPattern.Match(curLineText).Groups; var (untrimmedKey, key, value, severity, comment) = GetGroups(groups); // Verify the most recent header is a valid header if (IsValidHeader(mostRecentHeader, lastValidHeader) && string.Equals(key, optionName, StringComparison.OrdinalIgnoreCase)) { // We found the rule in the file -- replace it with updated option value. textChange = new TextChange(curLine.Span, $"{untrimmedKey}={optionValue}{comment}"); } } else if (s_headerPattern.IsMatch(curLineText.Trim())) { mostRecentHeader = curLine; if (ShouldSetAsLastValidHeader(curLineText, out var mostRecentHeaderText)) { lastValidHeader = mostRecentHeader; } else { var (fileName, splicedFileExtensions) = ParseHeaderParts(mostRecentHeaderText); if ((relativePath.IsEmpty() || new Regex(fileName).IsMatch(relativePath)) && HeaderMatchesLanguageRequirements(language, splicedFileExtensions)) { lastValidHeader = mostRecentHeader; } } } // We want to keep track of how far this (valid) section spans. if (IsValidHeader(mostRecentHeader, lastValidHeader) && IsNotEmptyOrComment(curLineText)) { lastValidHeaderSpanEnd = curLine; if (lastValidSpecificHeader != null && mostRecentHeader.Equals(lastValidSpecificHeader)) { lastValidSpecificHeaderSpanEnd = curLine; } } } // We return only the last text change in case of duplicate entries for the same rule. if (textChange != default) { return (editorConfigText.WithChanges(textChange), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } // Rule not found. return (null, lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); static (string untrimmedKey, string key, string value, string severitySuffixInValue, string commentValue) GetGroups(GroupCollection groups) { var untrimmedKey = groups[1].Value.ToString(); var key = untrimmedKey.Trim(); var value = groups[2].Value.ToString(); var severitySuffixInValue = groups[3].Value.ToString(); var commentValue = groups[4].Value.ToString(); return (untrimmedKey, key, value, severitySuffixInValue, commentValue); } static bool IsValidHeader(TextLine? mostRecentHeader, TextLine? lastValidHeader) { return mostRecentHeader is not null && lastValidHeader is not null && mostRecentHeader.Equals(lastValidHeader); } static bool ShouldSetAsLastValidHeader(string curLineText, out string mostRecentHeaderText) { var groups = s_headerPattern.Match(curLineText.Trim()).Groups; mostRecentHeaderText = groups[1].Value.ToString().ToLowerInvariant(); return mostRecentHeaderText.Equals("*", StringComparison.Ordinal); } static (string fileName, string[] splicedFileExtensions) ParseHeaderParts(string mostRecentHeaderText) { // We splice on the last occurrence of '.' to account for filenames containing periods. var nameExtensionSplitIndex = mostRecentHeaderText.LastIndexOf('.'); var fileName = mostRecentHeaderText.Substring(0, nameExtensionSplitIndex); var splicedFileExtensions = mostRecentHeaderText[(nameExtensionSplitIndex + 1)..].Split(',', ' ', '{', '}'); // Replacing characters in the header with the regex equivalent. fileName = fileName.Replace(".", @"\."); fileName = fileName.Replace("*", ".*"); fileName = fileName.Replace("/", @"\/"); return (fileName, splicedFileExtensions); } static bool IsNotEmptyOrComment(string currentLineText) { return !string.IsNullOrWhiteSpace(currentLineText) && !currentLineText.Trim().StartsWith("#", StringComparison.OrdinalIgnoreCase); } static bool HeaderMatchesLanguageRequirements(Language language, string[] splicedFileExtensions) { return IsCSharpOnly(language, splicedFileExtensions) || IsVisualBasicOnly(language, splicedFileExtensions) || IsBothVisualBasicAndCSharp(language, splicedFileExtensions); } static bool IsCSharpOnly(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.CSharp) && !language.HasFlag(Language.VisualBasic) && splicedFileExtensions.Contains("cs") && splicedFileExtensions.Length == 1; } static bool IsVisualBasicOnly(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.VisualBasic) && !language.HasFlag(Language.CSharp) && splicedFileExtensions.Contains("vb") && splicedFileExtensions.Length == 1; } static bool IsBothVisualBasicAndCSharp(Language language, string[] splicedFileExtensions) { return language.HasFlag(Language.VisualBasic) && language.HasFlag(Language.CSharp) && splicedFileExtensions.Contains("vb") && splicedFileExtensions.Contains("cs"); } } private static (SourceText? newText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd) AddMissingRule(SourceText editorConfigText, TextLine? lastValidHeaderSpanEnd, TextLine? lastValidSpecificHeaderSpanEnd, string optionName, string optionValue, Language language) { var newEntry = $"{optionName}={optionValue}"; if (lastValidSpecificHeaderSpanEnd.HasValue) { if (lastValidSpecificHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; // TODO(jmarolf): do we need to read in the users newline settings? } return (editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(lastValidSpecificHeaderSpanEnd.Value.Span.End, 0), newEntry)), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } else if (lastValidHeaderSpanEnd.HasValue) { if (lastValidHeaderSpanEnd.Value.ToString().Trim().Length != 0) { newEntry = "\r\n" + newEntry; // TODO(jmarolf): do we need to read in the users newline settings? } return (editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(lastValidHeaderSpanEnd.Value.Span.End, 0), newEntry)), lastValidHeaderSpanEnd, lastValidSpecificHeaderSpanEnd); } // We need to generate a new header such as '[*.cs]' or '[*.vb]': // - For compiler diagnostic entries and code style entries which have per-language option = false, generate only [*.cs] or [*.vb]. // - For the remainder, generate [*.{cs,vb}] // Insert a newline if not already present var lines = editorConfigText.Lines; var lastLine = lines.Count > 0 ? lines[^1] : default; var prefix = string.Empty; if (lastLine.ToString().Trim().Length != 0) { prefix = "\r\n"; } // Insert newline if file is not empty if (lines.Count > 1 && lastLine.ToString().Trim().Length == 0) { prefix += "\r\n"; } if (language.HasFlag(Language.CSharp) && language.HasFlag(Language.VisualBasic)) { prefix += "[*.{cs,vb}]\r\n"; } else if (language.HasFlag(Language.CSharp)) { prefix += "[*.cs]\r\n"; } else if (language.HasFlag(Language.VisualBasic)) { prefix += "[*.vb]\r\n"; } var result = editorConfigText.WithChanges((TextChange)new TextChange(new TextSpan(editorConfigText.Length, 0), prefix + newEntry)); return (result, lastValidHeaderSpanEnd, result.Lines[^2]); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Portable/Symbols/Source/SourceClonedParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a source parameter cloned from another <see cref="SourceParameterSymbol"/>, when they must share attribute data and default constant value. /// For example, parameters on a property symbol are cloned to generate parameters on accessors. /// Similarly parameters on delegate invoke method are cloned to delegate begin/end invoke methods. /// </summary> internal sealed class SourceClonedParameterSymbol : SourceParameterSymbolBase { // if true suppresses params-array and default value: private readonly bool _suppressOptional; private readonly SourceParameterSymbol _originalParam; internal SourceClonedParameterSymbol(SourceParameterSymbol originalParam, Symbol newOwner, int newOrdinal, bool suppressOptional) : base(newOwner, newOrdinal) { Debug.Assert((object)originalParam != null); _suppressOptional = suppressOptional; _originalParam = originalParam; } public override bool IsImplicitlyDeclared => true; public override bool IsDiscard => _originalParam.IsDiscard; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { // Since you can't get from the syntax node that represents the original parameter // back to this symbol we decided not to return the original syntax node here. return ImmutableArray<SyntaxReference>.Empty; } } public override bool IsParams { get { return !_suppressOptional && _originalParam.IsParams; } } internal override bool IsMetadataOptional { get { // pseudo-custom attributes are not suppressed: return _suppressOptional ? _originalParam.HasOptionalAttribute : _originalParam.IsMetadataOptional; } } internal override ConstantValue ExplicitDefaultConstantValue { get { // pseudo-custom attributes are not suppressed: return _suppressOptional ? _originalParam.DefaultValueFromAttributes : _originalParam.ExplicitDefaultConstantValue; } } internal override ConstantValue DefaultValueFromAttributes { get { return _originalParam.DefaultValueFromAttributes; } } internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams) { return new SourceClonedParameterSymbol( _originalParam.WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams), this.ContainingSymbol, this.Ordinal, _suppressOptional); } #region Forwarded public override TypeWithAnnotations TypeWithAnnotations { get { return _originalParam.TypeWithAnnotations; } } public override RefKind RefKind { get { return _originalParam.RefKind; } } internal override bool IsMetadataIn { get { return _originalParam.IsMetadataIn; } } internal override bool IsMetadataOut { get { return _originalParam.IsMetadataOut; } } public override ImmutableArray<Location> Locations { get { return _originalParam.Locations; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return _originalParam.GetAttributes(); } public sealed override string Name { get { return _originalParam.Name; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return _originalParam.RefCustomModifiers; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return _originalParam.MarshallingInformation; } } internal override bool IsIDispatchConstant { get { return _originalParam.IsIDispatchConstant; } } internal override bool IsIUnknownConstant { get { return _originalParam.IsIUnknownConstant; } } internal override bool IsCallerFilePath { get { return _originalParam.IsCallerFilePath; } } internal override bool IsCallerLineNumber { get { return _originalParam.IsCallerLineNumber; } } internal override bool IsCallerMemberName { get { return _originalParam.IsCallerMemberName; } } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return FlowAnalysisAnnotations.None; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull { get { return ImmutableHashSet<string>.Empty; } } internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => throw ExceptionUtilities.Unreachable; internal override bool HasInterpolatedStringHandlerArgumentError => throw ExceptionUtilities.Unreachable; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a source parameter cloned from another <see cref="SourceParameterSymbol"/>, when they must share attribute data and default constant value. /// For example, parameters on a property symbol are cloned to generate parameters on accessors. /// Similarly parameters on delegate invoke method are cloned to delegate begin/end invoke methods. /// </summary> internal sealed class SourceClonedParameterSymbol : SourceParameterSymbolBase { // if true suppresses params-array and default value: private readonly bool _suppressOptional; private readonly SourceParameterSymbol _originalParam; internal SourceClonedParameterSymbol(SourceParameterSymbol originalParam, Symbol newOwner, int newOrdinal, bool suppressOptional) : base(newOwner, newOrdinal) { Debug.Assert((object)originalParam != null); _suppressOptional = suppressOptional; _originalParam = originalParam; } public override bool IsImplicitlyDeclared => true; public override bool IsDiscard => _originalParam.IsDiscard; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { // Since you can't get from the syntax node that represents the original parameter // back to this symbol we decided not to return the original syntax node here. return ImmutableArray<SyntaxReference>.Empty; } } public override bool IsParams { get { return !_suppressOptional && _originalParam.IsParams; } } internal override bool IsMetadataOptional { get { // pseudo-custom attributes are not suppressed: return _suppressOptional ? _originalParam.HasOptionalAttribute : _originalParam.IsMetadataOptional; } } internal override ConstantValue ExplicitDefaultConstantValue { get { // pseudo-custom attributes are not suppressed: return _suppressOptional ? _originalParam.DefaultValueFromAttributes : _originalParam.ExplicitDefaultConstantValue; } } internal override ConstantValue DefaultValueFromAttributes { get { return _originalParam.DefaultValueFromAttributes; } } internal override ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams) { return new SourceClonedParameterSymbol( _originalParam.WithCustomModifiersAndParamsCore(newType, newCustomModifiers, newRefCustomModifiers, newIsParams), this.ContainingSymbol, this.Ordinal, _suppressOptional); } #region Forwarded public override TypeWithAnnotations TypeWithAnnotations { get { return _originalParam.TypeWithAnnotations; } } public override RefKind RefKind { get { return _originalParam.RefKind; } } internal override bool IsMetadataIn { get { return _originalParam.IsMetadataIn; } } internal override bool IsMetadataOut { get { return _originalParam.IsMetadataOut; } } public override ImmutableArray<Location> Locations { get { return _originalParam.Locations; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return _originalParam.GetAttributes(); } public sealed override string Name { get { return _originalParam.Name; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return _originalParam.RefCustomModifiers; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return _originalParam.MarshallingInformation; } } internal override bool IsIDispatchConstant { get { return _originalParam.IsIDispatchConstant; } } internal override bool IsIUnknownConstant { get { return _originalParam.IsIUnknownConstant; } } internal override bool IsCallerFilePath { get { return _originalParam.IsCallerFilePath; } } internal override bool IsCallerLineNumber { get { return _originalParam.IsCallerLineNumber; } } internal override bool IsCallerMemberName { get { return _originalParam.IsCallerMemberName; } } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return FlowAnalysisAnnotations.None; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull { get { return ImmutableHashSet<string>.Empty; } } internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => throw ExceptionUtilities.Unreachable; internal override bool HasInterpolatedStringHandlerArgumentError => throw ExceptionUtilities.Unreachable; #endregion } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Workspaces/CSharp/Portable/Simplification/Reducers/AbstractCSharpReducer.AbstractReductionRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal abstract partial class AbstractCSharpReducer { protected abstract class AbstractReductionRewriter : CSharpSyntaxRewriter, IReductionRewriter { private readonly ObjectPool<IReductionRewriter> _pool; protected CSharpParseOptions ParseOptions { get; private set; } protected OptionSet OptionSet { get; private set; } protected CancellationToken CancellationToken { get; private set; } protected SemanticModel SemanticModel { get; private set; } public bool HasMoreWork { get; private set; } // can be used to simplify whole subtrees while just annotating one syntax node. // This is e.g. useful in the name simplification, where a whole qualified name is annotated protected bool alwaysSimplify; private readonly HashSet<SyntaxNode> _processedParentNodes = new(); protected AbstractReductionRewriter(ObjectPool<IReductionRewriter> pool) => _pool = pool; public void Initialize(ParseOptions parseOptions, OptionSet optionSet, CancellationToken cancellationToken) { ParseOptions = (CSharpParseOptions)parseOptions; OptionSet = optionSet; CancellationToken = cancellationToken; } public void Dispose() { ParseOptions = null; OptionSet = null; CancellationToken = CancellationToken.None; _processedParentNodes.Clear(); SemanticModel = null; HasMoreWork = false; alwaysSimplify = false; _pool.Free(this); } private static SyntaxNode GetParentNode(SyntaxNode node) => node switch { ExpressionSyntax expression => GetParentNode(expression), PatternSyntax pattern => GetParentNode(pattern), CrefSyntax cref => GetParentNode(cref), _ => null }; private static SyntaxNode GetParentNode(ExpressionSyntax expression) { var lastExpression = expression; for (SyntaxNode current = expression; current != null; current = current.Parent) { if (current is ExpressionSyntax currentExpression) { lastExpression = currentExpression; } } return lastExpression.Parent; } private static SyntaxNode GetParentNode(PatternSyntax pattern) { var lastPattern = pattern; for (SyntaxNode current = pattern; current != null; current = current.Parent) { if (current is PatternSyntax currentPattern) { lastPattern = currentPattern; } } return lastPattern.Parent; } private static SyntaxNode GetParentNode(CrefSyntax cref) { var topMostCref = cref .AncestorsAndSelf() .OfType<CrefSyntax>() .LastOrDefault(); return topMostCref.Parent; } protected SyntaxNode SimplifyNode<TNode>( TNode node, SyntaxNode newNode, SyntaxNode parentNode, Func<TNode, SemanticModel, OptionSet, CancellationToken, SyntaxNode> simplifier) where TNode : SyntaxNode { Debug.Assert(parentNode != null); this.CancellationToken.ThrowIfCancellationRequested(); if (!this.alwaysSimplify && !node.HasAnnotation(Simplifier.Annotation)) { return newNode; } if (node != newNode || _processedParentNodes.Contains(parentNode)) { this.HasMoreWork = true; return newNode; } if (!node.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation)) { var simplifiedNode = simplifier(node, this.SemanticModel, this.OptionSet, this.CancellationToken); if (simplifiedNode != node) { _processedParentNodes.Add(parentNode); this.HasMoreWork = true; return simplifiedNode; } } return node; } protected SyntaxNode SimplifyExpression<TExpression>( TExpression expression, SyntaxNode newNode, Func<TExpression, SemanticModel, OptionSet, CancellationToken, SyntaxNode> simplifier) where TExpression : SyntaxNode { var parentNode = GetParentNode(expression); if (parentNode == null) return newNode; return SimplifyNode(expression, newNode, parentNode, simplifier); } protected SyntaxToken SimplifyToken(SyntaxToken token, Func<SyntaxToken, SemanticModel, OptionSet, CancellationToken, SyntaxToken> simplifier) { this.CancellationToken.ThrowIfCancellationRequested(); return token.HasAnnotation(Simplifier.Annotation) ? simplifier(token, this.SemanticModel, this.OptionSet, this.CancellationToken) : token; } public override SyntaxNode VisitElementAccessExpression(ElementAccessExpressionSyntax node) { // Note that we prefer simplifying the argument list before the expression var argumentList = (BracketedArgumentListSyntax)this.Visit(node.ArgumentList); var expression = (ExpressionSyntax)this.Visit(node.Expression); return node.Update(expression, argumentList); } public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node) { // Note that we prefer simplifying the argument list before the expression var argumentList = (ArgumentListSyntax)this.Visit(node.ArgumentList); var expression = (ExpressionSyntax)this.Visit(node.Expression); return node.Update(expression, argumentList); } public SyntaxNodeOrToken VisitNodeOrToken(SyntaxNodeOrToken nodeOrToken, SemanticModel semanticModel, bool simplifyAllDescendants) { this.SemanticModel = semanticModel; this.alwaysSimplify = simplifyAllDescendants; this.HasMoreWork = false; _processedParentNodes.Clear(); if (nodeOrToken.IsNode) { return Visit(nodeOrToken.AsNode()); } else { return VisitToken(nodeOrToken.AsToken()); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal abstract partial class AbstractCSharpReducer { protected abstract class AbstractReductionRewriter : CSharpSyntaxRewriter, IReductionRewriter { private readonly ObjectPool<IReductionRewriter> _pool; protected CSharpParseOptions ParseOptions { get; private set; } protected OptionSet OptionSet { get; private set; } protected CancellationToken CancellationToken { get; private set; } protected SemanticModel SemanticModel { get; private set; } public bool HasMoreWork { get; private set; } // can be used to simplify whole subtrees while just annotating one syntax node. // This is e.g. useful in the name simplification, where a whole qualified name is annotated protected bool alwaysSimplify; private readonly HashSet<SyntaxNode> _processedParentNodes = new(); protected AbstractReductionRewriter(ObjectPool<IReductionRewriter> pool) => _pool = pool; public void Initialize(ParseOptions parseOptions, OptionSet optionSet, CancellationToken cancellationToken) { ParseOptions = (CSharpParseOptions)parseOptions; OptionSet = optionSet; CancellationToken = cancellationToken; } public void Dispose() { ParseOptions = null; OptionSet = null; CancellationToken = CancellationToken.None; _processedParentNodes.Clear(); SemanticModel = null; HasMoreWork = false; alwaysSimplify = false; _pool.Free(this); } private static SyntaxNode GetParentNode(SyntaxNode node) => node switch { ExpressionSyntax expression => GetParentNode(expression), PatternSyntax pattern => GetParentNode(pattern), CrefSyntax cref => GetParentNode(cref), _ => null }; private static SyntaxNode GetParentNode(ExpressionSyntax expression) { var lastExpression = expression; for (SyntaxNode current = expression; current != null; current = current.Parent) { if (current is ExpressionSyntax currentExpression) { lastExpression = currentExpression; } } return lastExpression.Parent; } private static SyntaxNode GetParentNode(PatternSyntax pattern) { var lastPattern = pattern; for (SyntaxNode current = pattern; current != null; current = current.Parent) { if (current is PatternSyntax currentPattern) { lastPattern = currentPattern; } } return lastPattern.Parent; } private static SyntaxNode GetParentNode(CrefSyntax cref) { var topMostCref = cref .AncestorsAndSelf() .OfType<CrefSyntax>() .LastOrDefault(); return topMostCref.Parent; } protected SyntaxNode SimplifyNode<TNode>( TNode node, SyntaxNode newNode, SyntaxNode parentNode, Func<TNode, SemanticModel, OptionSet, CancellationToken, SyntaxNode> simplifier) where TNode : SyntaxNode { Debug.Assert(parentNode != null); this.CancellationToken.ThrowIfCancellationRequested(); if (!this.alwaysSimplify && !node.HasAnnotation(Simplifier.Annotation)) { return newNode; } if (node != newNode || _processedParentNodes.Contains(parentNode)) { this.HasMoreWork = true; return newNode; } if (!node.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation)) { var simplifiedNode = simplifier(node, this.SemanticModel, this.OptionSet, this.CancellationToken); if (simplifiedNode != node) { _processedParentNodes.Add(parentNode); this.HasMoreWork = true; return simplifiedNode; } } return node; } protected SyntaxNode SimplifyExpression<TExpression>( TExpression expression, SyntaxNode newNode, Func<TExpression, SemanticModel, OptionSet, CancellationToken, SyntaxNode> simplifier) where TExpression : SyntaxNode { var parentNode = GetParentNode(expression); if (parentNode == null) return newNode; return SimplifyNode(expression, newNode, parentNode, simplifier); } protected SyntaxToken SimplifyToken(SyntaxToken token, Func<SyntaxToken, SemanticModel, OptionSet, CancellationToken, SyntaxToken> simplifier) { this.CancellationToken.ThrowIfCancellationRequested(); return token.HasAnnotation(Simplifier.Annotation) ? simplifier(token, this.SemanticModel, this.OptionSet, this.CancellationToken) : token; } public override SyntaxNode VisitElementAccessExpression(ElementAccessExpressionSyntax node) { // Note that we prefer simplifying the argument list before the expression var argumentList = (BracketedArgumentListSyntax)this.Visit(node.ArgumentList); var expression = (ExpressionSyntax)this.Visit(node.Expression); return node.Update(expression, argumentList); } public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node) { // Note that we prefer simplifying the argument list before the expression var argumentList = (ArgumentListSyntax)this.Visit(node.ArgumentList); var expression = (ExpressionSyntax)this.Visit(node.Expression); return node.Update(expression, argumentList); } public SyntaxNodeOrToken VisitNodeOrToken(SyntaxNodeOrToken nodeOrToken, SemanticModel semanticModel, bool simplifyAllDescendants) { this.SemanticModel = semanticModel; this.alwaysSimplify = simplifyAllDescendants; this.HasMoreWork = false; _processedParentNodes.Clear(); if (nodeOrToken.IsNode) { return Visit(nodeOrToken.AsNode()); } else { return VisitToken(nodeOrToken.AsToken()); } } } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/Core/Portable/InternalUtilities/StringTable.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.Text; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; #if DEBUG using System.Diagnostics; #endif namespace Roslyn.Utilities { /// <summary> /// This is basically a lossy cache of strings that is searchable by /// strings, string sub ranges, character array ranges or string-builder. /// </summary> internal class StringTable { // entry in the caches private struct Entry { // hash code of the entry public int HashCode; // full text of the item public string Text; } // TODO: Need to tweak the size with more scenarios. // for now this is what works well enough with // Roslyn C# compiler project // Size of local cache. private const int LocalSizeBits = 11; private const int LocalSize = (1 << LocalSizeBits); private const int LocalSizeMask = LocalSize - 1; // max size of shared cache. private const int SharedSizeBits = 16; private const int SharedSize = (1 << SharedSizeBits); private const int SharedSizeMask = SharedSize - 1; // size of bucket in shared cache. (local cache has bucket size 1). private const int SharedBucketBits = 4; private const int SharedBucketSize = (1 << SharedBucketBits); private const int SharedBucketSizeMask = SharedBucketSize - 1; // local (L1) cache // simple fast and not threadsafe cache // with limited size and "last add wins" expiration policy // // The main purpose of the local cache is to use in long lived // single threaded operations with lots of locality (like parsing). // Local cache is smaller (and thus faster) and is not affected // by cache misses on other threads. private readonly Entry[] _localTable = new Entry[LocalSize]; // shared (L2) threadsafe cache // slightly slower than local cache // we read this cache when having a miss in local cache // writes to local cache will update shared cache as well. private static readonly Entry[] s_sharedTable = new Entry[SharedSize]; // essentially a random number // the usage pattern will randomly use and increment this // the counter is not static to avoid interlocked operations and cross-thread traffic private int _localRandom = Environment.TickCount; // same as above but for users that go directly with unbuffered shared cache. private static int s_sharedRandom = Environment.TickCount; internal StringTable() : this(null) { } // implement Poolable object pattern #region "Poolable" private StringTable(ObjectPool<StringTable>? pool) { _pool = pool; } private readonly ObjectPool<StringTable>? _pool; private static readonly ObjectPool<StringTable> s_staticPool = CreatePool(); private static ObjectPool<StringTable> CreatePool() { var pool = new ObjectPool<StringTable>(pool => new StringTable(pool), Environment.ProcessorCount * 2); return pool; } public static StringTable GetInstance() { return s_staticPool.Allocate(); } public void Free() { // leave cache content in the cache, just return it to the pool // Array.Clear(this.localTable, 0, this.localTable.Length); // Array.Clear(sharedTable, 0, sharedTable.Length); _pool?.Free(this); } #endregion // Poolable internal string Add(char[] chars, int start, int len) { var span = chars.AsSpan(start, len); var hashCode = Hash.GetFNVHashCode(chars, start, len); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, span)) { return result; } } string? shared = FindSharedEntry(chars, start, len, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, start, len, hashCode); } internal string Add(string chars, int start, int len) { var hashCode = Hash.GetFNVHashCode(chars, start, len); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, chars, start, len)) { return result; } } string? shared = FindSharedEntry(chars, start, len, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, start, len, hashCode); } internal string Add(char chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null) { var result = arr[idx].Text; if (text.Length == 1 && text[0] == chars) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, hashCode); } internal string Add(StringBuilder chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, chars)) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, hashCode); } internal string Add(string chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (result == chars) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } AddCore(chars, hashCode); return chars; } private static string? FindSharedEntry(char[] chars, int start, int len, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars.AsSpan(start, len))) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(string chars, int start, int len, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars, start, len)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntryASCII(int hashCode, ReadOnlySpan<byte> asciiChars) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEqualsASCII(e, asciiChars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(char chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; if (e != null) { if (e.Length == 1 && e[0] == chars) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(StringBuilder chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(string chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && e == chars) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private string AddItem(char[] chars, int start, int len, int hashCode) { var text = new String(chars, start, len); AddCore(text, hashCode); return text; } private string AddItem(string chars, int start, int len, int hashCode) { var text = chars.Substring(start, len); AddCore(text, hashCode); return text; } private string AddItem(char chars, int hashCode) { var text = new String(chars, 1); AddCore(text, hashCode); return text; } private string AddItem(StringBuilder chars, int hashCode) { var text = chars.ToString(); AddCore(text, hashCode); return text; } private void AddCore(string chars, int hashCode) { // add to the shared table first (in case someone looks for same item) AddSharedEntry(hashCode, chars); // add to the local table too var arr = _localTable; var idx = LocalIdxFromHash(hashCode); arr[idx].HashCode = hashCode; arr[idx].Text = chars; } private void AddSharedEntry(int hashCode, string text) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Text == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = LocalNextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Text, text); } internal static string AddShared(StringBuilder chars) { var hashCode = Hash.GetFNVHashCode(chars); string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { return shared; } return AddSharedSlow(hashCode, chars); } private static string AddSharedSlow(int hashCode, StringBuilder builder) { string text = builder.ToString(); AddSharedSlow(hashCode, text); return text; } internal static string AddSharedUTF8(ReadOnlySpan<byte> bytes) { int hashCode = Hash.GetFNVHashCode(bytes, out bool isAscii); if (isAscii) { string? shared = FindSharedEntryASCII(hashCode, bytes); if (shared != null) { return shared; } } return AddSharedSlow(hashCode, bytes, isAscii); } private static string AddSharedSlow(int hashCode, ReadOnlySpan<byte> utf8Bytes, bool isAscii) { string text; unsafe { fixed (byte* bytes = &utf8Bytes.GetPinnableReference()) { text = Encoding.UTF8.GetString(bytes, utf8Bytes.Length); } } // Don't add non-ascii strings to table. The hashCode we have here is not correct and we won't find them again. // Non-ascii in UTF8-encoded parts of metadata (the only use of this at the moment) is assumed to be rare in // practice. If that turns out to be wrong, we could decode to pooled memory and rehash here. if (isAscii) { AddSharedSlow(hashCode, text); } return text; } private static void AddSharedSlow(int hashCode, string text) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Text == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = SharedNextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Text, text); } private static int LocalIdxFromHash(int hash) { return hash & LocalSizeMask; } private static int SharedIdxFromHash(int hash) { // we can afford to mix some more hash bits here return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask; } private int LocalNextRandom() { return _localRandom++; } private static int SharedNextRandom() { return Interlocked.Increment(ref StringTable.s_sharedRandom); } internal static bool TextEquals(string array, string text, int start, int length) { if (array.Length != length) { return false; } // use array.Length to eliminate the range check for (var i = 0; i < array.Length; i++) { if (array[i] != text[start + i]) { return false; } } return true; } internal static bool TextEquals(string array, StringBuilder text) { if (array.Length != text.Length) { return false; } // interestingly, stringbuilder holds the list of chunks by the tail // so accessing positions at the beginning may cost more than those at the end. for (var i = array.Length - 1; i >= 0; i--) { if (array[i] != text[i]) { return false; } } return true; } internal static bool TextEqualsASCII(string text, ReadOnlySpan<byte> ascii) { #if DEBUG for (var i = 0; i < ascii.Length; i++) { Debug.Assert((ascii[i] & 0x80) == 0, $"The {nameof(ascii)} input to this method must be valid ASCII."); } #endif if (ascii.Length != text.Length) { return false; } for (var i = 0; i < ascii.Length; i++) { if (ascii[i] != text[i]) { return false; } } return true; } internal static bool TextEquals(string array, ReadOnlySpan<char> text) => text.Equals(array.AsSpan(), StringComparison.Ordinal); } }
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; #if DEBUG using System.Diagnostics; #endif namespace Roslyn.Utilities { /// <summary> /// This is basically a lossy cache of strings that is searchable by /// strings, string sub ranges, character array ranges or string-builder. /// </summary> internal class StringTable { // entry in the caches private struct Entry { // hash code of the entry public int HashCode; // full text of the item public string Text; } // TODO: Need to tweak the size with more scenarios. // for now this is what works well enough with // Roslyn C# compiler project // Size of local cache. private const int LocalSizeBits = 11; private const int LocalSize = (1 << LocalSizeBits); private const int LocalSizeMask = LocalSize - 1; // max size of shared cache. private const int SharedSizeBits = 16; private const int SharedSize = (1 << SharedSizeBits); private const int SharedSizeMask = SharedSize - 1; // size of bucket in shared cache. (local cache has bucket size 1). private const int SharedBucketBits = 4; private const int SharedBucketSize = (1 << SharedBucketBits); private const int SharedBucketSizeMask = SharedBucketSize - 1; // local (L1) cache // simple fast and not threadsafe cache // with limited size and "last add wins" expiration policy // // The main purpose of the local cache is to use in long lived // single threaded operations with lots of locality (like parsing). // Local cache is smaller (and thus faster) and is not affected // by cache misses on other threads. private readonly Entry[] _localTable = new Entry[LocalSize]; // shared (L2) threadsafe cache // slightly slower than local cache // we read this cache when having a miss in local cache // writes to local cache will update shared cache as well. private static readonly Entry[] s_sharedTable = new Entry[SharedSize]; // essentially a random number // the usage pattern will randomly use and increment this // the counter is not static to avoid interlocked operations and cross-thread traffic private int _localRandom = Environment.TickCount; // same as above but for users that go directly with unbuffered shared cache. private static int s_sharedRandom = Environment.TickCount; internal StringTable() : this(null) { } // implement Poolable object pattern #region "Poolable" private StringTable(ObjectPool<StringTable>? pool) { _pool = pool; } private readonly ObjectPool<StringTable>? _pool; private static readonly ObjectPool<StringTable> s_staticPool = CreatePool(); private static ObjectPool<StringTable> CreatePool() { var pool = new ObjectPool<StringTable>(pool => new StringTable(pool), Environment.ProcessorCount * 2); return pool; } public static StringTable GetInstance() { return s_staticPool.Allocate(); } public void Free() { // leave cache content in the cache, just return it to the pool // Array.Clear(this.localTable, 0, this.localTable.Length); // Array.Clear(sharedTable, 0, sharedTable.Length); _pool?.Free(this); } #endregion // Poolable internal string Add(char[] chars, int start, int len) { var span = chars.AsSpan(start, len); var hashCode = Hash.GetFNVHashCode(chars, start, len); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, span)) { return result; } } string? shared = FindSharedEntry(chars, start, len, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, start, len, hashCode); } internal string Add(string chars, int start, int len) { var hashCode = Hash.GetFNVHashCode(chars, start, len); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, chars, start, len)) { return result; } } string? shared = FindSharedEntry(chars, start, len, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, start, len, hashCode); } internal string Add(char chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null) { var result = arr[idx].Text; if (text.Length == 1 && text[0] == chars) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, hashCode); } internal string Add(StringBuilder chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, chars)) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, hashCode); } internal string Add(string chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (result == chars) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } AddCore(chars, hashCode); return chars; } private static string? FindSharedEntry(char[] chars, int start, int len, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars.AsSpan(start, len))) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(string chars, int start, int len, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars, start, len)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntryASCII(int hashCode, ReadOnlySpan<byte> asciiChars) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEqualsASCII(e, asciiChars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(char chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; if (e != null) { if (e.Length == 1 && e[0] == chars) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(StringBuilder chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(string chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && e == chars) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private string AddItem(char[] chars, int start, int len, int hashCode) { var text = new String(chars, start, len); AddCore(text, hashCode); return text; } private string AddItem(string chars, int start, int len, int hashCode) { var text = chars.Substring(start, len); AddCore(text, hashCode); return text; } private string AddItem(char chars, int hashCode) { var text = new String(chars, 1); AddCore(text, hashCode); return text; } private string AddItem(StringBuilder chars, int hashCode) { var text = chars.ToString(); AddCore(text, hashCode); return text; } private void AddCore(string chars, int hashCode) { // add to the shared table first (in case someone looks for same item) AddSharedEntry(hashCode, chars); // add to the local table too var arr = _localTable; var idx = LocalIdxFromHash(hashCode); arr[idx].HashCode = hashCode; arr[idx].Text = chars; } private void AddSharedEntry(int hashCode, string text) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Text == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = LocalNextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Text, text); } internal static string AddShared(StringBuilder chars) { var hashCode = Hash.GetFNVHashCode(chars); string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { return shared; } return AddSharedSlow(hashCode, chars); } private static string AddSharedSlow(int hashCode, StringBuilder builder) { string text = builder.ToString(); AddSharedSlow(hashCode, text); return text; } internal static string AddSharedUTF8(ReadOnlySpan<byte> bytes) { int hashCode = Hash.GetFNVHashCode(bytes, out bool isAscii); if (isAscii) { string? shared = FindSharedEntryASCII(hashCode, bytes); if (shared != null) { return shared; } } return AddSharedSlow(hashCode, bytes, isAscii); } private static string AddSharedSlow(int hashCode, ReadOnlySpan<byte> utf8Bytes, bool isAscii) { string text; unsafe { fixed (byte* bytes = &utf8Bytes.GetPinnableReference()) { text = Encoding.UTF8.GetString(bytes, utf8Bytes.Length); } } // Don't add non-ascii strings to table. The hashCode we have here is not correct and we won't find them again. // Non-ascii in UTF8-encoded parts of metadata (the only use of this at the moment) is assumed to be rare in // practice. If that turns out to be wrong, we could decode to pooled memory and rehash here. if (isAscii) { AddSharedSlow(hashCode, text); } return text; } private static void AddSharedSlow(int hashCode, string text) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Text == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = SharedNextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Text, text); } private static int LocalIdxFromHash(int hash) { return hash & LocalSizeMask; } private static int SharedIdxFromHash(int hash) { // we can afford to mix some more hash bits here return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask; } private int LocalNextRandom() { return _localRandom++; } private static int SharedNextRandom() { return Interlocked.Increment(ref StringTable.s_sharedRandom); } internal static bool TextEquals(string array, string text, int start, int length) { if (array.Length != length) { return false; } // use array.Length to eliminate the range check for (var i = 0; i < array.Length; i++) { if (array[i] != text[start + i]) { return false; } } return true; } internal static bool TextEquals(string array, StringBuilder text) { if (array.Length != text.Length) { return false; } // interestingly, stringbuilder holds the list of chunks by the tail // so accessing positions at the beginning may cost more than those at the end. for (var i = array.Length - 1; i >= 0; i--) { if (array[i] != text[i]) { return false; } } return true; } internal static bool TextEqualsASCII(string text, ReadOnlySpan<byte> ascii) { #if DEBUG for (var i = 0; i < ascii.Length; i++) { Debug.Assert((ascii[i] & 0x80) == 0, $"The {nameof(ascii)} input to this method must be valid ASCII."); } #endif if (ascii.Length != text.Length) { return false; } for (var i = 0; i < ascii.Length; i++) { if (ascii[i] != text[i]) { return false; } } return true; } internal static bool TextEquals(string array, ReadOnlySpan<char> text) => text.Equals(array.AsSpan(), StringComparison.Ordinal); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hans.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../CodeAnalysisResources.resx"> <body> <trans-unit id="A_language_name_cannot_be_specified_for_this_option"> <source>A language name cannot be specified for this option.</source> <target state="translated">无法为此选项指定语言名称。</target> <note /> </trans-unit> <trans-unit id="A_language_name_must_be_specified_for_this_option"> <source>A language name must be specified for this option.</source> <target state="translated">必须为此选项指定语言名称。</target> <note /> </trans-unit> <trans-unit id="AssemblyReferencesNetFramework"> <source>The assembly containing type '{0}' references .NET Framework, which is not supported.</source> <target state="translated">包含类型“{0}”的程序集引用了 .NET Framework,而此操作不受支持。</target> <note /> </trans-unit> <trans-unit id="ChangesMustBeWithinBoundsOfSourceText"> <source>Changes must be within bounds of SourceText</source> <target state="translated">必须在 SourceText 的边界内进行更改</target> <note /> </trans-unit> <trans-unit id="ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging"> <source>Changing the version of an assembly reference is not allowed during debugging: '{0}' changed version to '{1}'.</source> <target state="translated">调试过程中不允许更改程序集引用的版本:“{0}”版本改为“{1}”。</target> <note /> </trans-unit> <trans-unit id="CompilerAnalyzerThrowsDescription"> <source>Analyzer '{0}' threw the following exception: '{1}'.</source> <target state="translated">分析器“{0}”引发了以下异常: “{1}”。</target> <note /> </trans-unit> <trans-unit id="DisableAnalyzerDiagnosticsMessage"> <source>Suppress the following diagnostics to disable this analyzer: {0}</source> <target state="translated">取消以下诊断以禁用此分析器: {0}</target> <note>{0}: Comma-separated list of diagnostic IDs</note> </trans-unit> <trans-unit id="HintNameInvalidChar"> <source>The hintName '{0}' contains an invalid character '{1}' at position {2}.</source> <target state="new">The hintName '{0}' contains an invalid character '{1}' at position {2}.</target> <note>{0}: the provided hintname. {1}: the invalid character, {2} the position it occurred at</note> </trans-unit> <trans-unit id="HintNameUniquePerGenerator"> <source>The hintName '{0}' of the added source file must be unique within a generator.</source> <target state="new">The hintName '{0}' of the added source file must be unique within a generator.</target> <note>{0}: the provided hintname</note> </trans-unit> <trans-unit id="InvalidAdditionalFile"> <source>Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'.</source> <target state="translated">其他文件不属于基础 "CompilationWithAnalyzers"。</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticSuppressionReported"> <source>Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor.</source> <target state="translated">对于给定的禁止显示描述符,禁止显示的诊断 ID“{0}”与可禁止显示的 ID“{1}”不匹配。</target> <note /> </trans-unit> <trans-unit id="InvalidOperationBlockForAnalysisContext"> <source>Given operation block does not belong to the current analysis context.</source> <target state="translated">给定操作块不属于当前的分析上下文。</target> <note /> </trans-unit> <trans-unit id="IsSymbolAccessibleBadWithin"> <source>Parameter '{0}' must be an 'INamedTypeSymbol' or an 'IAssemblySymbol'.</source> <target state="translated">参数“{0}”必须是 "INamedTypeSymbol 或 "IAssemblySymbol"。</target> <note /> </trans-unit> <trans-unit id="IsSymbolAccessibleWrongAssembly"> <source>Parameter '{0}' must be a symbol from this compilation or some referenced assembly.</source> <target state="translated">参数“{0}”必须是此编译或某些引用程序集的符号。</target> <note /> </trans-unit> <trans-unit id="ModuleHasInvalidAttributes"> <source>Module has invalid attributes.</source> <target state="translated">模块具有无效属性。</target> <note /> </trans-unit> <trans-unit id="NonReportedDiagnosticCannotBeSuppressed"> <source>Non-reported diagnostic with ID '{0}' cannot be suppressed.</source> <target state="translated">不可禁止显示 ID 为“{0}”的未报告的诊断。</target> <note /> </trans-unit> <trans-unit id="NotARootOperation"> <source>Given operation has a non-null parent.</source> <target state="translated">给定操作具有一个非 null 父级。</target> <note /> </trans-unit> <trans-unit id="OperationHasNullSemanticModel"> <source>Given operation has a null semantic model.</source> <target state="translated">给定操作具有一个 null 语义模型。</target> <note /> </trans-unit> <trans-unit id="OperationMustNotBeControlFlowGraphPart"> <source>The provided operation must not be part of a Control Flow Graph.</source> <target state="translated">提供的操作不能是控制流图的一部分。</target> <note /> </trans-unit> <trans-unit id="OutputKindNotSupported"> <source>Output kind not supported.</source> <target state="translated">输出类型不受支持。</target> <note /> </trans-unit> <trans-unit id="PathReturnedByResolveMetadataFileMustBeAbsolute"> <source>Path returned by {0}.ResolveMetadataFile must be absolute: '{1}'</source> <target state="translated">由 {0}.ResolveMetadataFile 返回的路径必须是绝对路径:“{1}”</target> <note /> </trans-unit> <trans-unit id="AssemblyMustHaveAtLeastOneModule"> <source>Assembly must have at least one module.</source> <target state="translated">程序集必须有至少一个模块。</target> <note /> </trans-unit> <trans-unit id="ModuleCopyCannotBeUsedToCreateAssemblyMetadata"> <source>Module copy can't be used to create an assembly metadata.</source> <target state="translated">模块复制不能用于创建程序集元数据。</target> <note /> </trans-unit> <trans-unit id="Single_type_per_generator_0"> <source>Only a single {0} can be registered per generator.</source> <target state="translated">每个生成器仅可注册一个 {0}。</target> <note>{0}: type name</note> </trans-unit> <trans-unit id="SourceTextRequiresEncoding"> <source>The SourceText with hintName '{0}' must have an explicit encoding set.</source> <target state="new">The SourceText with hintName '{0}' must have an explicit encoding set.</target> <note>'SourceText' is not localizable. {0}: the provided hintname</note> </trans-unit> <trans-unit id="SupportedDiagnosticsHasNullDescriptor"> <source>Analyzer '{0}' contains a null descriptor in its 'SupportedDiagnostics'.</source> <target state="translated">分析器“{0}”在其 "SupportedDiagnostics" 中包含 null 描述符。</target> <note /> </trans-unit> <trans-unit id="SupportedSuppressionsHasNullDescriptor"> <source>Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'.</source> <target state="translated">分析器“{0}”在其 "SupportedSuppressions" 中包含 null 描述符。</target> <note /> </trans-unit> <trans-unit id="SuppressionDiagnosticDescriptorMessage"> <source>Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}'</source> <target state="translated">具有禁止显示 ID {2} 和理由“{3}”的 DiagnosticSuppressor 已以编程方式禁止显示诊断“{0}: {1}”</target> <note /> </trans-unit> <trans-unit id="SuppressionDiagnosticDescriptorTitle"> <source>Programmatic suppression of an analyzer diagnostic</source> <target state="translated">以编程方式禁止显示分析器诊断</target> <note /> </trans-unit> <trans-unit id="SuppressionIdCantBeNullOrWhitespace"> <source>A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</source> <target state="translated">A SuppressionDescriptor 必须具有一个 ID,且该 ID 不为 null、不是空字符串且不是仅包含空格的字符串。</target> <note /> </trans-unit> <trans-unit id="TupleElementNullableAnnotationCountMismatch"> <source>If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple.</source> <target state="translated">如果已指定元组元素可以为 null 的注释,则注释的数量必须与元组基数相匹配。</target> <note /> </trans-unit> <trans-unit id="UnableToDetermineSpecificCauseOfFailure"> <source>Unable to determine specific cause of the failure.</source> <target state="translated">无法确定失败的具体原因。</target> <note /> </trans-unit> <trans-unit id="Unresolved"> <source>Unresolved: </source> <target state="translated">未解析:</target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>assembly</source> <target state="translated">程序集</target> <note /> </trans-unit> <trans-unit id="Class1"> <source>class</source> <target state="translated">类</target> <note /> </trans-unit> <trans-unit id="Constructor"> <source>constructor</source> <target state="translated">构造函数</target> <note /> </trans-unit> <trans-unit id="Delegate1"> <source>delegate</source> <target state="translated">委托</target> <note /> </trans-unit> <trans-unit id="Enum1"> <source>enum</source> <target state="translated">枚举</target> <note /> </trans-unit> <trans-unit id="Event1"> <source>event</source> <target state="translated">事件</target> <note /> </trans-unit> <trans-unit id="Field"> <source>field</source> <target state="translated">字段</target> <note /> </trans-unit> <trans-unit id="TypeParameter"> <source>type parameter</source> <target state="translated">类型形参</target> <note /> </trans-unit> <trans-unit id="Interface1"> <source>interface</source> <target state="translated">接口</target> <note /> </trans-unit> <trans-unit id="Method"> <source>method</source> <target state="translated">方法</target> <note /> </trans-unit> <trans-unit id="Module"> <source>module</source> <target state="translated">模块</target> <note /> </trans-unit> <trans-unit id="Parameter"> <source>parameter</source> <target state="translated">参数</target> <note /> </trans-unit> <trans-unit id="Property"> <source>property, indexer</source> <target state="translated">属性、索引器</target> <note /> </trans-unit> <trans-unit id="Return1"> <source>return</source> <target state="translated">返回</target> <note /> </trans-unit> <trans-unit id="Struct1"> <source>struct</source> <target state="translated">结构</target> <note /> </trans-unit> <trans-unit id="CannotCreateReferenceToSubmission"> <source>Can't create a reference to a submission.</source> <target state="translated">不能创建对提交的引用。</target> <note /> </trans-unit> <trans-unit id="CannotCreateReferenceToModule"> <source>Can't create a reference to a module.</source> <target state="translated">不能创建对模块的引用。</target> <note /> </trans-unit> <trans-unit id="InMemoryAssembly"> <source>&lt;in-memory assembly&gt;</source> <target state="translated">&lt;内存中的程序集&gt;</target> <note /> </trans-unit> <trans-unit id="InMemoryModule"> <source>&lt;in-memory module&gt;</source> <target state="translated">&lt;内存中的模块&gt;</target> <note /> </trans-unit> <trans-unit id="SizeHasToBePositive"> <source>Size has to be positive.</source> <target state="translated">大小必须为正数。</target> <note /> </trans-unit> <trans-unit id="AssemblyFileNotFound"> <source>Assembly file not found</source> <target state="translated">未找到程序集文件</target> <note /> </trans-unit> <trans-unit id="CannotEmbedInteropTypesFromModule"> <source>Can't embed interop types from module.</source> <target state="translated">不能从模块嵌入互操作类型。</target> <note /> </trans-unit> <trans-unit id="CannotAliasModule"> <source>Can't alias a module.</source> <target state="translated">不能给模块起别名。</target> <note /> </trans-unit> <trans-unit id="InvalidAlias"> <source>Invalid alias.</source> <target state="translated">无效别名。</target> <note /> </trans-unit> <trans-unit id="GetMetadataMustReturnInstance"> <source>{0}.GetMetadata() must return an instance of {1}.</source> <target state="translated">{0}.GetMetadata() 必须返回 {1} 的实例。</target> <note /> </trans-unit> <trans-unit id="UnsupportedSuppressionReported"> <source>Reported suppression with ID '{0}' is not supported by the suppressor.</source> <target state="translated">抑制器不支持已报告的 ID 为“{0}”的诊断。</target> <note /> </trans-unit> <trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer"> <source>Value too large to be represented as a 30 bit unsigned integer.</source> <target state="translated">值太大,无法表示为 30 位无符号整数。</target> <note /> </trans-unit> <trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized"> <source>Arrays with more than one dimension cannot be serialized.</source> <target state="translated">不能序列化具有多个维度的数组。</target> <note /> </trans-unit> <trans-unit id="InvalidAssemblyName"> <source>Invalid assembly name: '{0}'</source> <target state="translated">无效程序集名称: “{0}”</target> <note /> </trans-unit> <trans-unit id="AbsolutePathExpected"> <source>Absolute path expected.</source> <target state="translated">预期的绝对路径。</target> <note /> </trans-unit> <trans-unit id="EmptyKeyInPathMap"> <source>A key in the pathMap is empty.</source> <target state="translated">pathMap 中的键为空。</target> <note /> </trans-unit> <trans-unit id="NullValueInPathMap"> <source>A value in the pathMap is null.</source> <target state="translated">pathMap 中的一个值为 null。</target> <note /> </trans-unit> <trans-unit id="CompilationOptionsMustNotHaveErrors"> <source>Compilation options must not have errors.</source> <target state="translated">编译选项必须无错误。</target> <note /> </trans-unit> <trans-unit id="ReturnTypeCannotBeValuePointerbyRefOrOpen"> <source>Return type can't be a value type, pointer, by-ref or open generic type</source> <target state="translated">返回类型不能是值类型、指针、引用传递或开放式泛型类型</target> <note /> </trans-unit> <trans-unit id="ReturnTypeCannotBeVoidByRefOrOpen"> <source>Return type can't be void, by-ref or open generic type</source> <target state="translated">返回类型不能是无效、引用传递或是开放式泛型类型</target> <note /> </trans-unit> <trans-unit id="TypeMustBeSameAsHostObjectTypeOfPreviousSubmission"> <source>Type must be same as host object type of previous submission.</source> <target state="translated">类型须与之前提交的宿主对象的类型相同。</target> <note /> </trans-unit> <trans-unit id="PreviousSubmissionHasErrors"> <source>Previous submission has errors.</source> <target state="translated">上一个提交有错误。</target> <note /> </trans-unit> <trans-unit id="InvalidOutputKindForSubmission"> <source>Invalid output kind for submission. DynamicallyLinkedLibrary expected.</source> <target state="translated">无效的提交输出类型。预期为 DynamicallyLinkedLibrary。</target> <note /> </trans-unit> <trans-unit id="InvalidCompilationOptions"> <source>Invalid compilation options -- submission can't be signed.</source> <target state="translated">无效的编译选项 -- 不能签署提交。</target> <note /> </trans-unit> <trans-unit id="ResourceStreamProviderShouldReturnNonNullStream"> <source>Resource stream provider should return non-null stream.</source> <target state="translated">资源流提供程序应返回非空流。</target> <note /> </trans-unit> <trans-unit id="ReferenceResolverShouldReturnReadableNonNullStream"> <source>Reference resolver should return readable non-null stream.</source> <target state="translated">引用解析程序应返回非空的可读流。</target> <note /> </trans-unit> <trans-unit id="EmptyOrInvalidResourceName"> <source>Empty or invalid resource name</source> <target state="translated">空的或无效的资源名</target> <note /> </trans-unit> <trans-unit id="EmptyOrInvalidFileName"> <source>Empty or invalid file name</source> <target state="translated">空的或无效的文件名</target> <note /> </trans-unit> <trans-unit id="ResourceDataProviderShouldReturnNonNullStream"> <source>Resource data provider should return non-null stream</source> <target state="translated">资源数据提供程序应返回非空流</target> <note /> </trans-unit> <trans-unit id="FileNotFound"> <source>File not found.</source> <target state="translated">未找到文件。</target> <note /> </trans-unit> <trans-unit id="PathReturnedByResolveStrongNameKeyFileMustBeAbsolute"> <source>Path returned by {0}.ResolveStrongNameKeyFile must be absolute: '{1}'</source> <target state="translated">由 {0}.ResolveStrongNameKeyFile 返回的路径必须是绝对路径:“{1}”</target> <note /> </trans-unit> <trans-unit id="TypeMustBeASubclassOfSyntaxAnnotation"> <source>type must be a subclass of SyntaxAnnotation.</source> <target state="translated">类型必须是 SyntaxAnnotation 的子类。</target> <note /> </trans-unit> <trans-unit id="InvalidModuleName"> <source>Invalid module name specified in metadata module '{0}': '{1}'</source> <target state="translated">在元数据模块“{0}”中所指定的模块名称无效:“{1}”</target> <note /> </trans-unit> <trans-unit id="FileSizeExceedsMaximumAllowed"> <source>File size exceeds maximum allowed size of a valid metadata file.</source> <target state="translated">文件大小超过有效元数据文件所允许的最大大小。</target> <note /> </trans-unit> <trans-unit id="NameCannotBeNull"> <source>Name cannot be null.</source> <target state="translated">名称不能为 null。</target> <note /> </trans-unit> <trans-unit id="NameCannotBeEmpty"> <source>Name cannot be empty.</source> <target state="translated">名称不能为空。</target> <note /> </trans-unit> <trans-unit id="NameCannotStartWithWhitespace"> <source>Name cannot start with whitespace.</source> <target state="translated">名称不能以空格开头。</target> <note /> </trans-unit> <trans-unit id="NameContainsInvalidCharacter"> <source>Name contains invalid characters.</source> <target state="translated">名称包含无效字符。</target> <note /> </trans-unit> <trans-unit id="SpanDoesNotIncludeStartOfLine"> <source>The span does not include the start of a line.</source> <target state="translated">范围不包括行的开头。</target> <note /> </trans-unit> <trans-unit id="SpanDoesNotIncludeEndOfLine"> <source>The span does not include the end of a line.</source> <target state="translated">范围不包括行的末尾。</target> <note /> </trans-unit> <trans-unit id="StartMustNotBeNegative"> <source>'start' must not be negative</source> <target state="translated">'“开始”不能为负</target> <note /> </trans-unit> <trans-unit id="EndMustNotBeLessThanStart"> <source>'end' must not be less than 'start'</source> <target state="translated">'“结束时间”不得早于“开始时间”</target> <note /> </trans-unit> <trans-unit id="InvalidContentType"> <source>Invalid content type</source> <target state="translated">无效的内容类型</target> <note /> </trans-unit> <trans-unit id="ExpectedNonEmptyPublicKey"> <source>Expected non-empty public key</source> <target state="translated">预期的非空公钥</target> <note /> </trans-unit> <trans-unit id="InvalidSizeOfPublicKeyToken"> <source>Invalid size of public key token.</source> <target state="translated">公钥标记的大小无效。</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyName"> <source>Invalid characters in assembly name</source> <target state="translated">程序集名称中有无效字符</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyCultureName"> <source>Invalid characters in assembly culture name</source> <target state="translated">程序集区域性名称中有无效字符</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportReadAndSeek"> <source>Stream must support read and seek operations.</source> <target state="translated">流必须支持读取和搜寻操作。</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportRead"> <source>Stream must be readable.</source> <target state="translated">流必须为可读。</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportWrite"> <source>Stream must be writable.</source> <target state="translated">流必须是可写的。</target> <note /> </trans-unit> <trans-unit id="PdbStreamUnexpectedWhenEmbedding"> <source>PDB stream should not be given when embedding PDB into the PE stream.</source> <target state="translated">将 PE 流嵌入 PDB 时,无法提供 PDB 流。</target> <note /> </trans-unit> <trans-unit id="PdbStreamUnexpectedWhenEmittingMetadataOnly"> <source>PDB stream should not be given when emitting metadata only.</source> <target state="translated">仅发出元数据时不应提供 PDB 流。</target> <note /> </trans-unit> <trans-unit id="MetadataPeStreamUnexpectedWhenEmittingMetadataOnly"> <source>Metadata PE stream should not be given when emitting metadata only.</source> <target state="translated">仅发出元数据时不应提供元数据 PE 流。</target> <note /> </trans-unit> <trans-unit id="IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream"> <source>Including private members should not be used when emitting to the secondary assembly output.</source> <target state="translated">发出到辅助程序集输出时不应包含私有成员。</target> <note /> </trans-unit> <trans-unit id="MustIncludePrivateMembersUnlessRefAssembly"> <source>Must include private members unless emitting a ref assembly.</source> <target state="translated">必须包括私有成员,除非发出 ref 程序集。</target> <note /> </trans-unit> <trans-unit id="EmbeddingPdbUnexpectedWhenEmittingMetadata"> <source>Embedding PDB is not allowed when emitting metadata.</source> <target state="translated">不允许在发出元数据时嵌入 PDB。</target> <note /> </trans-unit> <trans-unit id="CannotTargetNetModuleWhenEmittingRefAssembly"> <source>Cannot target net module when emitting ref assembly.</source> <target state="translated">无法在发出引用程序集时将 Net 模块作为目标。</target> <note /> </trans-unit> <trans-unit id="InvalidHash"> <source>Invalid hash.</source> <target state="translated">哈希无效。</target> <note /> </trans-unit> <trans-unit id="UnsupportedHashAlgorithm"> <source>Unsupported hash algorithm.</source> <target state="translated">不支持的哈希算法。</target> <note /> </trans-unit> <trans-unit id="InconsistentLanguageVersions"> <source>Inconsistent language versions</source> <target state="translated">不一致的语言版本</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidRelocation"> <source>Win32 resources, assumed to be in COFF object format, have one or more invalid relocation header values.</source> <target state="translated">Win32 资源,假定为 COFF 对象格式,具有一个或多个无效的重定位标头值。</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidSectionSize"> <source>Win32 resources, assumed to be in COFF object format, have an invalid section size.</source> <target state="translated">Win32 资源,假定为 COFF 对象格式,具有一个无效的节大小。</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidSymbol"> <source>Win32 resources, assumed to be in COFF object format, have one or more invalid symbol values.</source> <target state="translated">Win32 资源,假定为 COFF 对象格式,具有一个或多个无效的符号值。</target> <note /> </trans-unit> <trans-unit id="CoffResourceMissingSection"> <source>Win32 resources, assumed to be in COFF object format, are missing one or both of sections '.rsrc$01' and '.rsrc$02'</source> <target state="translated">Win32 资源,假定为 COFF 对象格式,缺少其中一个或全部两个节:“.rsrc$01” 和“.rsrc$02”</target> <note /> </trans-unit> <trans-unit id="IconStreamUnexpectedFormat"> <source>Icon stream is not in the expected format.</source> <target state="translated">图标流不是预期格式。</target> <note /> </trans-unit> <trans-unit id="InvalidCultureName"> <source>Invalid culture name: '{0}'</source> <target state="translated">无效的区域性名称:“{0}”</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidGlobalSectionName"> <source>Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}'</source> <target state="translated">全局分析器配置部分名称“{0}”无效,因为它不是绝对路径。部分将被忽略。部分已在以下文件中声明:“{1}”。</target> <note>{0}: invalid section name, {1} path to global config</note> </trans-unit> <trans-unit id="WRN_InvalidGlobalSectionName_Title"> <source>Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored.</source> <target state="translated">全局分析器配置部分名称无效,因为它不是绝对路径。部分将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSeverityInAnalyzerConfig"> <source>The diagnostic '{0}' was given an invalid severity '{1}' in the analyzer config file at '{2}'.</source> <target state="translated">在 "{2}" 的分析器配置文件中为诊断 "{0}" 给定了无效的严重性 "{1}"。</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSeverityInAnalyzerConfig_Title"> <source>Invalid severity in analyzer config file.</source> <target state="translated">分析器配置文件中的严重性无效。</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleGlobalAnalyzerKeys"> <source>Multiple global analyzer config files set the same key '{0}' in section '{1}'. It has been unset. Key was set by the following files: '{2}'</source> <target state="translated">多个全局分析器配置文件在“{1}”部分中设置了相同的密钥“{0}”。它已取消设置。密钥由以下文件设置:“{2}”</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleGlobalAnalyzerKeys_Title"> <source>Multiple global analyzer config files set the same key. It has been unset.</source> <target state="translated">多个全局分析器配置文件设置了相同的密钥。它已取消设置。</target> <note /> </trans-unit> <trans-unit id="WinRTIdentityCantBeRetargetable"> <source>WindowsRuntime identity can't be retargetable</source> <target state="translated">WindowsRuntime 标识不可重定目标</target> <note /> </trans-unit> <trans-unit id="PEImageNotAvailable"> <source>PE image not available.</source> <target state="translated">PE 映像不可用。</target> <note /> </trans-unit> <trans-unit id="AssemblySigningNotSupported"> <source>Assembly signing not supported.</source> <target state="translated">不支持程序集签名。</target> <note /> </trans-unit> <trans-unit id="XmlReferencesNotSupported"> <source>References to XML documents are not supported.</source> <target state="translated">不支持 XML 文档的引用。</target> <note /> </trans-unit> <trans-unit id="FailedToResolveRuleSetName"> <source>Could not locate the rule set file '{0}'.</source> <target state="translated">未能找到规则集文件“{0}”。</target> <note /> </trans-unit> <trans-unit id="InvalidRuleSetInclude"> <source>An error occurred while loading the included rule set file {0} - {1}</source> <target state="translated">加载所含规则集文件 {0} - {1} 时出错</target> <note /> </trans-unit> <trans-unit id="CompilerAnalyzerFailure"> <source>Analyzer Failure</source> <target state="translated">分析器故障</target> <note>{0}: Analyzer name {1}: Type name {2}: Localized exception message {3}: Localized detail message</note> </trans-unit> <trans-unit id="CompilerAnalyzerThrows"> <source>Analyzer '{0}' threw an exception of type '{1}' with message '{2}'. {3}</source> <target state="translated">分析器“{0}”引发类型为“{1}”的异常,并显示消息“{2}”。 {3}</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverFailure"> <source>Analyzer Driver Failure</source> <target state="translated">分析器驱动程序故障</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverThrows"> <source>Analyzer driver threw an exception of type '{0}' with message '{1}'.</source> <target state="translated">分析器驱动程序抛出类型为“{0}”的异常,并显示消息“{1}”。</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverThrowsDescription"> <source>Analyzer driver threw the following exception: '{0}'.</source> <target state="translated">分析器驱动程序抛出以下异常: “{0}”。</target> <note /> </trans-unit> <trans-unit id="PEImageDoesntContainManagedMetadata"> <source>PE image doesn't contain managed metadata.</source> <target state="translated">PE 映像不包含任何托管元数据。</target> <note /> </trans-unit> <trans-unit id="ChangesMustNotOverlap"> <source>The changes must not overlap.</source> <target state="translated">更改必须有序且不重叠。</target> <note /> </trans-unit> <trans-unit id="DiagnosticIdCantBeNullOrWhitespace"> <source>A DiagnosticDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</source> <target state="translated">DiagnosticDescriptor 必须有一个 ID,该 ID 不能为 null、空字符串或只包含空格的字符串。</target> <note /> </trans-unit> <trans-unit id="RuleSetHasDuplicateRules"> <source>The rule set file has duplicate rules for '{0}' with differing actions '{1}' and '{2}'.</source> <target state="translated">规则集文件对有不同操作 “{1}” 和“{2}”的“{0}”有重复规则。</target> <note /> </trans-unit> <trans-unit id="CantCreateModuleReferenceToAssembly"> <source>Can't create a module reference to an assembly.</source> <target state="translated">无法对程序集创建模块引用.</target> <note /> </trans-unit> <trans-unit id="CantCreateReferenceToDynamicAssembly"> <source>Can't create a metadata reference to a dynamic assembly.</source> <target state="translated">无法对动态程序集创建元数据引用。</target> <note /> </trans-unit> <trans-unit id="CantCreateReferenceToAssemblyWithoutLocation"> <source>Can't create a metadata reference to an assembly without location.</source> <target state="translated">无法对不含位置的程序集创建元数据引用。</target> <note /> </trans-unit> <trans-unit id="ArgumentCannotBeEmpty"> <source>Argument cannot be empty.</source> <target state="translated">参数不能为空。</target> <note /> </trans-unit> <trans-unit id="ArgumentElementCannotBeNull"> <source>Argument cannot have a null element.</source> <target state="translated">参数不能具有 null 元素。</target> <note /> </trans-unit> <trans-unit id="UnsupportedDiagnosticReported"> <source>Reported diagnostic with ID '{0}' is not supported by the analyzer.</source> <target state="translated">分析器不支持 ID 为“{0}”的报告的诊断。</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticIdReported"> <source>Reported diagnostic has an ID '{0}', which is not a valid identifier.</source> <target state="translated">报告的诊断 ID“{0}”不是有效的标识符。</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticLocationReported"> <source>Reported diagnostic '{0}' has a source location in file '{1}', which is not part of the compilation being analyzed.</source> <target state="translated">报告的诊断“{0}”的源位置位于文件“{1}”中,后者不是要分析的编译的一部分。</target> <note /> </trans-unit> <trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder"> <source>The type '{0}' is not understood by the serialization binder.</source> <target state="translated">序列化绑定器不理解“{0}”类型。</target> <note /> </trans-unit> <trans-unit id="Cannot_deserialize_type_0"> <source>Cannot deserialize type '{0}'.</source> <target state="translated">无法反序列化类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="Cannot_serialize_type_0"> <source>Cannot serialize type '{0}'.</source> <target state="translated">无法序列化类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="InvalidNodeToTrack"> <source>Node to track is not a descendant of the root.</source> <target state="translated">要跟踪的节点不是根的后代。</target> <note /> </trans-unit> <trans-unit id="NodeOrTokenOutOfSequence"> <source>A node or token is out of sequence.</source> <target state="translated">某个节点或标记的顺序不正确。</target> <note /> </trans-unit> <trans-unit id="UnexpectedTypeOfNodeInList"> <source>A node in the list is not of the expected type.</source> <target state="translated">列表中的某个节点不是预期的类型。</target> <note /> </trans-unit> <trans-unit id="MissingListItem"> <source>The item specified is not the element of a list.</source> <target state="translated">指定的项不是列表的元素。</target> <note /> </trans-unit> <trans-unit id="InvalidPublicKey"> <source>Invalid public key.</source> <target state="translated">公钥无效</target> <note /> </trans-unit> <trans-unit id="InvalidPublicKeyToken"> <source>Invalid public key token.</source> <target state="translated">公钥标记无效。</target> <note /> </trans-unit> <trans-unit id="InvalidDataAtOffset"> <source>Invalid data at offset {0}: {1}{2}*{3}{4}</source> <target state="translated">偏移量 {0} 处的数据无效: {1}{2}*{3}{4}</target> <note /> </trans-unit> <trans-unit id="SymWriterNotDeterministic"> <source>Windows PDB writer doesn't support deterministic compilation: '{0}'</source> <target state="translated">Windows PDB 编写器不支持确定性的编译:“{0}”</target> <note /> </trans-unit> <trans-unit id="SymWriterOlderVersionThanRequired"> <source>The version of Windows PDB writer is older than required: '{0}'</source> <target state="translated">Windows PDB 编写器的版本早于要求的版本:“{0}”</target> <note /> </trans-unit> <trans-unit id="SymWriterDoesNotSupportSourceLink"> <source>Windows PDB writer doesn't support SourceLink feature: '{0}'</source> <target state="translated">Windows PDB 编写器不支持 SourceLink 功能:“{0}”</target> <note /> </trans-unit> <trans-unit id="RuleSetBadAttributeValue"> <source>The attribute {0} has an invalid value of {1}.</source> <target state="translated">属性 {0} 具有无效值 {1}。</target> <note /> </trans-unit> <trans-unit id="RuleSetMissingAttribute"> <source>The element {0} is missing an attribute named {1}.</source> <target state="translated">元素 {0} 缺少名为 {1} 的属性。</target> <note /> </trans-unit> <trans-unit id="KeepAliveIsNotAnInteger"> <source>Argument to '/keepalive' option is not a 32-bit integer.</source> <target state="translated">"/keepalive" 选项的参数不是一个 32 位整数。</target> <note /> </trans-unit> <trans-unit id="KeepAliveIsTooSmall"> <source>Arguments to '/keepalive' option below -1 are invalid.</source> <target state="translated">小于 -1 的 "/keepalive" 选项的参数无效。</target> <note /> </trans-unit> <trans-unit id="KeepAliveWithoutShared"> <source>'/keepalive' option is only valid with '/shared' option.</source> <target state="translated">'"/keepalive" 选项仅在与 "/shared" 选项一起使用时有效。</target> <note /> </trans-unit> <trans-unit id="MismatchedVersion"> <source>Roslyn compiler server reports different protocol version than build task.</source> <target state="translated">Roslyn 编译器服务器报告不同于生成任务的协议版本。</target> <note /> </trans-unit> <trans-unit id="MissingKeepAlive"> <source>Missing argument for '/keepalive' option.</source> <target state="translated">缺少 "/keepalive" 选项的参数。</target> <note /> </trans-unit> <trans-unit id="AnalyzerTotalExecutionTime"> <source>Total analyzer execution time: {0} seconds.</source> <target state="translated">分析器总执行时间: {0} 秒。</target> <note /> </trans-unit> <trans-unit id="MultithreadedAnalyzerExecutionNote"> <source>NOTE: Elapsed time may be less than analyzer execution time because analyzers can run concurrently.</source> <target state="translated">注意: 运行时间可能小于分析器执行时间,因为分析器可以同时运行。</target> <note /> </trans-unit> <trans-unit id="AnalyzerExecutionTimeColumnHeader"> <source>Time (s)</source> <target state="translated">时间(秒)</target> <note /> </trans-unit> <trans-unit id="AnalyzerNameColumnHeader"> <source>Analyzer</source> <target state="translated">分析器</target> <note /> </trans-unit> <trans-unit id="NoAnalyzersFound"> <source>No analyzers found</source> <target state="translated">找不到分析器</target> <note /> </trans-unit> <trans-unit id="DuplicateAnalyzerInstances"> <source>Argument contains duplicate analyzer instances.</source> <target state="translated">参数包含重复的分析器实例。</target> <note /> </trans-unit> <trans-unit id="UnsupportedAnalyzerInstance"> <source>Argument contains an analyzer instance that does not belong to the 'Analyzers' for this CompilationWithAnalyzers instance.</source> <target state="translated">参数包含的分析器实例不属于此 CompilationWithAnalyzers 实例的“Analyzers”。</target> <note /> </trans-unit> <trans-unit id="InvalidTree"> <source>Syntax tree doesn't belong to the underlying 'Compilation'.</source> <target state="translated">语法树不属于底层“Compilation”。</target> <note /> </trans-unit> <trans-unit id="ResourceStreamEndedUnexpectedly"> <source>Resource stream ended at {0} bytes, expected {1} bytes.</source> <target state="translated">资源流在 {0} 字节结束,预期为 {1} 字节。</target> <note /> </trans-unit> <trans-unit id="SharedArgumentMissing"> <source>Value for argument '/shared:' must not be empty</source> <target state="translated">参数“/shared:”的值不能为空</target> <note /> </trans-unit> <trans-unit id="ExceptionContext"> <source>Exception occurred with following context: {0}</source> <target state="translated">出现异常,上下文如下: {0}</target> <note /> </trans-unit> <trans-unit id="AnonymousTypeMemberAndNamesCountMismatch2"> <source>{0} and {1} must have the same length.</source> <target state="translated">{0} 和 {1} 长度必须相同。</target> <note /> </trans-unit> <trans-unit id="AnonymousTypeArgumentCountMismatch2"> <source>{0} must either be 'default' or have the same length as {1}.</source> <target state="translated">{0} 必须为“默认值”或具有与 {1} 相同的长度。</target> <note /> </trans-unit> <trans-unit id="InconsistentSyntaxTreeFeature"> <source>Inconsistent syntax tree features</source> <target state="translated">不一致的语法树特征</target> <note /> </trans-unit> <trans-unit id="ReferenceOfTypeIsInvalid1"> <source>Reference of type '{0}' is not valid for this compilation.</source> <target state="translated">引用类型“{0}”对该编译无效。</target> <note /> </trans-unit> <trans-unit id="MetadataRefNotFoundToRemove1"> <source>MetadataReference '{0}' not found to remove.</source> <target state="translated">未找到要删除的 MetadataReference“{0}”。</target> <note /> </trans-unit> <trans-unit id="TupleElementNameCountMismatch"> <source>If tuple element names are specified, the number of element names must match the cardinality of the tuple.</source> <target state="translated">如果指定了元组元素名称,元素名称的数量必须与元组基数相匹配。</target> <note /> </trans-unit> <trans-unit id="TupleElementNameEmpty"> <source>Tuple element name cannot be an empty string.</source> <target state="translated">元组元素名称不能为空字符串。</target> <note /> </trans-unit> <trans-unit id="TupleElementLocationCountMismatch"> <source>If tuple element locations are specified, the number of locations must match the cardinality of the tuple.</source> <target state="translated">如果已指定元组元素位置,则位置的数量必须与元组基数相匹配。</target> <note /> </trans-unit> <trans-unit id="TuplesNeedAtLeastTwoElements"> <source>Tuples must have at least two elements.</source> <target state="translated">元组必须包含至少两个元素。</target> <note /> </trans-unit> <trans-unit id="CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion"> <source>The compilation references multiple assemblies whose versions only differ in auto-generated build and/or revision numbers.</source> <target state="translated">编译将引用多个程序集(其版本只在自动生成的版本和/或修订号方面有所不同)。</target> <note /> </trans-unit> <trans-unit id="TupleUnderlyingTypeMustBeTupleCompatible"> <source>The underlying type for a tuple must be tuple-compatible.</source> <target state="translated">元组的基础类型必须符合元组。</target> <note /> </trans-unit> <trans-unit id="UnrecognizedResourceFileFormat"> <source>Unrecognized resource file format.</source> <target state="translated">无法识别的资源文件格式。</target> <note /> </trans-unit> <trans-unit id="SourceTextCannotBeEmbedded"> <source>SourceText cannot be embedded. Provide encoding or canBeEmbedded=true at construction.</source> <target state="translated">不能嵌入 SourceText。在构造时提供编码或 canBeEmbedded=true。</target> <note /> </trans-unit> <trans-unit id="StreamIsTooLong"> <source>Stream is too long.</source> <target state="translated">“流”过长。</target> <note /> </trans-unit> <trans-unit id="EmbeddedTextsRequirePdb"> <source>Embedded texts are only supported when emitting a PDB.</source> <target state="translated">仅在发出 PDB 时才支持嵌入的文本。</target> <note /> </trans-unit> <trans-unit id="TheStreamCannotBeWrittenTo"> <source>The stream cannot be written to.</source> <target state="translated">无法向流中写入。</target> <note /> </trans-unit> <trans-unit id="ElementIsExpected"> <source>element is expected</source> <target state="translated">应为元素</target> <note /> </trans-unit> <trans-unit id="SeparatorIsExpected"> <source>separator is expected</source> <target state="translated">需要分隔符</target> <note /> </trans-unit> <trans-unit id="TheStreamCannotBeReadFrom"> <source>The stream cannot be read from.</source> <target state="translated">无法从流中读取。</target> <note /> </trans-unit> <trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values"> <source>Deserialization reader for '{0}' read incorrect number of values.</source> <target state="translated">“{0}”的反序列化读取器读取到错误数量的值。</target> <note /> </trans-unit> <trans-unit id="Stream_contains_invalid_data"> <source>Stream contains invalid data</source> <target state="translated">流包含无效的数据</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticSpanReported"> <source>Reported diagnostic '{0}' has a source location '{1}' in file '{2}', which is outside of the given file.</source> <target state="translated">报告的诊断“{0}”的源位置“{1}”位于文件“{2}”中,后者不是给定文件。</target> <note /> </trans-unit> <trans-unit id="ExceptionEnablingMulticoreJit"> <source>Warning: Could not enable multicore JIT due to exception: {0}.</source> <target state="translated">警告: 无法启用 multicore JIT,因为存在异常: {0}。</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../CodeAnalysisResources.resx"> <body> <trans-unit id="A_language_name_cannot_be_specified_for_this_option"> <source>A language name cannot be specified for this option.</source> <target state="translated">无法为此选项指定语言名称。</target> <note /> </trans-unit> <trans-unit id="A_language_name_must_be_specified_for_this_option"> <source>A language name must be specified for this option.</source> <target state="translated">必须为此选项指定语言名称。</target> <note /> </trans-unit> <trans-unit id="AssemblyReferencesNetFramework"> <source>The assembly containing type '{0}' references .NET Framework, which is not supported.</source> <target state="translated">包含类型“{0}”的程序集引用了 .NET Framework,而此操作不受支持。</target> <note /> </trans-unit> <trans-unit id="ChangesMustBeWithinBoundsOfSourceText"> <source>Changes must be within bounds of SourceText</source> <target state="translated">必须在 SourceText 的边界内进行更改</target> <note /> </trans-unit> <trans-unit id="ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging"> <source>Changing the version of an assembly reference is not allowed during debugging: '{0}' changed version to '{1}'.</source> <target state="translated">调试过程中不允许更改程序集引用的版本:“{0}”版本改为“{1}”。</target> <note /> </trans-unit> <trans-unit id="CompilerAnalyzerThrowsDescription"> <source>Analyzer '{0}' threw the following exception: '{1}'.</source> <target state="translated">分析器“{0}”引发了以下异常: “{1}”。</target> <note /> </trans-unit> <trans-unit id="DisableAnalyzerDiagnosticsMessage"> <source>Suppress the following diagnostics to disable this analyzer: {0}</source> <target state="translated">取消以下诊断以禁用此分析器: {0}</target> <note>{0}: Comma-separated list of diagnostic IDs</note> </trans-unit> <trans-unit id="HintNameInvalidChar"> <source>The hintName '{0}' contains an invalid character '{1}' at position {2}.</source> <target state="new">The hintName '{0}' contains an invalid character '{1}' at position {2}.</target> <note>{0}: the provided hintname. {1}: the invalid character, {2} the position it occurred at</note> </trans-unit> <trans-unit id="HintNameUniquePerGenerator"> <source>The hintName '{0}' of the added source file must be unique within a generator.</source> <target state="new">The hintName '{0}' of the added source file must be unique within a generator.</target> <note>{0}: the provided hintname</note> </trans-unit> <trans-unit id="InvalidAdditionalFile"> <source>Additional file doesn't belong to the underlying 'CompilationWithAnalyzers'.</source> <target state="translated">其他文件不属于基础 "CompilationWithAnalyzers"。</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticSuppressionReported"> <source>Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor.</source> <target state="translated">对于给定的禁止显示描述符,禁止显示的诊断 ID“{0}”与可禁止显示的 ID“{1}”不匹配。</target> <note /> </trans-unit> <trans-unit id="InvalidOperationBlockForAnalysisContext"> <source>Given operation block does not belong to the current analysis context.</source> <target state="translated">给定操作块不属于当前的分析上下文。</target> <note /> </trans-unit> <trans-unit id="IsSymbolAccessibleBadWithin"> <source>Parameter '{0}' must be an 'INamedTypeSymbol' or an 'IAssemblySymbol'.</source> <target state="translated">参数“{0}”必须是 "INamedTypeSymbol 或 "IAssemblySymbol"。</target> <note /> </trans-unit> <trans-unit id="IsSymbolAccessibleWrongAssembly"> <source>Parameter '{0}' must be a symbol from this compilation or some referenced assembly.</source> <target state="translated">参数“{0}”必须是此编译或某些引用程序集的符号。</target> <note /> </trans-unit> <trans-unit id="ModuleHasInvalidAttributes"> <source>Module has invalid attributes.</source> <target state="translated">模块具有无效属性。</target> <note /> </trans-unit> <trans-unit id="NonReportedDiagnosticCannotBeSuppressed"> <source>Non-reported diagnostic with ID '{0}' cannot be suppressed.</source> <target state="translated">不可禁止显示 ID 为“{0}”的未报告的诊断。</target> <note /> </trans-unit> <trans-unit id="NotARootOperation"> <source>Given operation has a non-null parent.</source> <target state="translated">给定操作具有一个非 null 父级。</target> <note /> </trans-unit> <trans-unit id="OperationHasNullSemanticModel"> <source>Given operation has a null semantic model.</source> <target state="translated">给定操作具有一个 null 语义模型。</target> <note /> </trans-unit> <trans-unit id="OperationMustNotBeControlFlowGraphPart"> <source>The provided operation must not be part of a Control Flow Graph.</source> <target state="translated">提供的操作不能是控制流图的一部分。</target> <note /> </trans-unit> <trans-unit id="OutputKindNotSupported"> <source>Output kind not supported.</source> <target state="translated">输出类型不受支持。</target> <note /> </trans-unit> <trans-unit id="PathReturnedByResolveMetadataFileMustBeAbsolute"> <source>Path returned by {0}.ResolveMetadataFile must be absolute: '{1}'</source> <target state="translated">由 {0}.ResolveMetadataFile 返回的路径必须是绝对路径:“{1}”</target> <note /> </trans-unit> <trans-unit id="AssemblyMustHaveAtLeastOneModule"> <source>Assembly must have at least one module.</source> <target state="translated">程序集必须有至少一个模块。</target> <note /> </trans-unit> <trans-unit id="ModuleCopyCannotBeUsedToCreateAssemblyMetadata"> <source>Module copy can't be used to create an assembly metadata.</source> <target state="translated">模块复制不能用于创建程序集元数据。</target> <note /> </trans-unit> <trans-unit id="Single_type_per_generator_0"> <source>Only a single {0} can be registered per generator.</source> <target state="translated">每个生成器仅可注册一个 {0}。</target> <note>{0}: type name</note> </trans-unit> <trans-unit id="SourceTextRequiresEncoding"> <source>The SourceText with hintName '{0}' must have an explicit encoding set.</source> <target state="new">The SourceText with hintName '{0}' must have an explicit encoding set.</target> <note>'SourceText' is not localizable. {0}: the provided hintname</note> </trans-unit> <trans-unit id="SupportedDiagnosticsHasNullDescriptor"> <source>Analyzer '{0}' contains a null descriptor in its 'SupportedDiagnostics'.</source> <target state="translated">分析器“{0}”在其 "SupportedDiagnostics" 中包含 null 描述符。</target> <note /> </trans-unit> <trans-unit id="SupportedSuppressionsHasNullDescriptor"> <source>Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'.</source> <target state="translated">分析器“{0}”在其 "SupportedSuppressions" 中包含 null 描述符。</target> <note /> </trans-unit> <trans-unit id="SuppressionDiagnosticDescriptorMessage"> <source>Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}'</source> <target state="translated">具有禁止显示 ID {2} 和理由“{3}”的 DiagnosticSuppressor 已以编程方式禁止显示诊断“{0}: {1}”</target> <note /> </trans-unit> <trans-unit id="SuppressionDiagnosticDescriptorTitle"> <source>Programmatic suppression of an analyzer diagnostic</source> <target state="translated">以编程方式禁止显示分析器诊断</target> <note /> </trans-unit> <trans-unit id="SuppressionIdCantBeNullOrWhitespace"> <source>A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</source> <target state="translated">A SuppressionDescriptor 必须具有一个 ID,且该 ID 不为 null、不是空字符串且不是仅包含空格的字符串。</target> <note /> </trans-unit> <trans-unit id="TupleElementNullableAnnotationCountMismatch"> <source>If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple.</source> <target state="translated">如果已指定元组元素可以为 null 的注释,则注释的数量必须与元组基数相匹配。</target> <note /> </trans-unit> <trans-unit id="UnableToDetermineSpecificCauseOfFailure"> <source>Unable to determine specific cause of the failure.</source> <target state="translated">无法确定失败的具体原因。</target> <note /> </trans-unit> <trans-unit id="Unresolved"> <source>Unresolved: </source> <target state="translated">未解析:</target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>assembly</source> <target state="translated">程序集</target> <note /> </trans-unit> <trans-unit id="Class1"> <source>class</source> <target state="translated">类</target> <note /> </trans-unit> <trans-unit id="Constructor"> <source>constructor</source> <target state="translated">构造函数</target> <note /> </trans-unit> <trans-unit id="Delegate1"> <source>delegate</source> <target state="translated">委托</target> <note /> </trans-unit> <trans-unit id="Enum1"> <source>enum</source> <target state="translated">枚举</target> <note /> </trans-unit> <trans-unit id="Event1"> <source>event</source> <target state="translated">事件</target> <note /> </trans-unit> <trans-unit id="Field"> <source>field</source> <target state="translated">字段</target> <note /> </trans-unit> <trans-unit id="TypeParameter"> <source>type parameter</source> <target state="translated">类型形参</target> <note /> </trans-unit> <trans-unit id="Interface1"> <source>interface</source> <target state="translated">接口</target> <note /> </trans-unit> <trans-unit id="Method"> <source>method</source> <target state="translated">方法</target> <note /> </trans-unit> <trans-unit id="Module"> <source>module</source> <target state="translated">模块</target> <note /> </trans-unit> <trans-unit id="Parameter"> <source>parameter</source> <target state="translated">参数</target> <note /> </trans-unit> <trans-unit id="Property"> <source>property, indexer</source> <target state="translated">属性、索引器</target> <note /> </trans-unit> <trans-unit id="Return1"> <source>return</source> <target state="translated">返回</target> <note /> </trans-unit> <trans-unit id="Struct1"> <source>struct</source> <target state="translated">结构</target> <note /> </trans-unit> <trans-unit id="CannotCreateReferenceToSubmission"> <source>Can't create a reference to a submission.</source> <target state="translated">不能创建对提交的引用。</target> <note /> </trans-unit> <trans-unit id="CannotCreateReferenceToModule"> <source>Can't create a reference to a module.</source> <target state="translated">不能创建对模块的引用。</target> <note /> </trans-unit> <trans-unit id="InMemoryAssembly"> <source>&lt;in-memory assembly&gt;</source> <target state="translated">&lt;内存中的程序集&gt;</target> <note /> </trans-unit> <trans-unit id="InMemoryModule"> <source>&lt;in-memory module&gt;</source> <target state="translated">&lt;内存中的模块&gt;</target> <note /> </trans-unit> <trans-unit id="SizeHasToBePositive"> <source>Size has to be positive.</source> <target state="translated">大小必须为正数。</target> <note /> </trans-unit> <trans-unit id="AssemblyFileNotFound"> <source>Assembly file not found</source> <target state="translated">未找到程序集文件</target> <note /> </trans-unit> <trans-unit id="CannotEmbedInteropTypesFromModule"> <source>Can't embed interop types from module.</source> <target state="translated">不能从模块嵌入互操作类型。</target> <note /> </trans-unit> <trans-unit id="CannotAliasModule"> <source>Can't alias a module.</source> <target state="translated">不能给模块起别名。</target> <note /> </trans-unit> <trans-unit id="InvalidAlias"> <source>Invalid alias.</source> <target state="translated">无效别名。</target> <note /> </trans-unit> <trans-unit id="GetMetadataMustReturnInstance"> <source>{0}.GetMetadata() must return an instance of {1}.</source> <target state="translated">{0}.GetMetadata() 必须返回 {1} 的实例。</target> <note /> </trans-unit> <trans-unit id="UnsupportedSuppressionReported"> <source>Reported suppression with ID '{0}' is not supported by the suppressor.</source> <target state="translated">抑制器不支持已报告的 ID 为“{0}”的诊断。</target> <note /> </trans-unit> <trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer"> <source>Value too large to be represented as a 30 bit unsigned integer.</source> <target state="translated">值太大,无法表示为 30 位无符号整数。</target> <note /> </trans-unit> <trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized"> <source>Arrays with more than one dimension cannot be serialized.</source> <target state="translated">不能序列化具有多个维度的数组。</target> <note /> </trans-unit> <trans-unit id="InvalidAssemblyName"> <source>Invalid assembly name: '{0}'</source> <target state="translated">无效程序集名称: “{0}”</target> <note /> </trans-unit> <trans-unit id="AbsolutePathExpected"> <source>Absolute path expected.</source> <target state="translated">预期的绝对路径。</target> <note /> </trans-unit> <trans-unit id="EmptyKeyInPathMap"> <source>A key in the pathMap is empty.</source> <target state="translated">pathMap 中的键为空。</target> <note /> </trans-unit> <trans-unit id="NullValueInPathMap"> <source>A value in the pathMap is null.</source> <target state="translated">pathMap 中的一个值为 null。</target> <note /> </trans-unit> <trans-unit id="CompilationOptionsMustNotHaveErrors"> <source>Compilation options must not have errors.</source> <target state="translated">编译选项必须无错误。</target> <note /> </trans-unit> <trans-unit id="ReturnTypeCannotBeValuePointerbyRefOrOpen"> <source>Return type can't be a value type, pointer, by-ref or open generic type</source> <target state="translated">返回类型不能是值类型、指针、引用传递或开放式泛型类型</target> <note /> </trans-unit> <trans-unit id="ReturnTypeCannotBeVoidByRefOrOpen"> <source>Return type can't be void, by-ref or open generic type</source> <target state="translated">返回类型不能是无效、引用传递或是开放式泛型类型</target> <note /> </trans-unit> <trans-unit id="TypeMustBeSameAsHostObjectTypeOfPreviousSubmission"> <source>Type must be same as host object type of previous submission.</source> <target state="translated">类型须与之前提交的宿主对象的类型相同。</target> <note /> </trans-unit> <trans-unit id="PreviousSubmissionHasErrors"> <source>Previous submission has errors.</source> <target state="translated">上一个提交有错误。</target> <note /> </trans-unit> <trans-unit id="InvalidOutputKindForSubmission"> <source>Invalid output kind for submission. DynamicallyLinkedLibrary expected.</source> <target state="translated">无效的提交输出类型。预期为 DynamicallyLinkedLibrary。</target> <note /> </trans-unit> <trans-unit id="InvalidCompilationOptions"> <source>Invalid compilation options -- submission can't be signed.</source> <target state="translated">无效的编译选项 -- 不能签署提交。</target> <note /> </trans-unit> <trans-unit id="ResourceStreamProviderShouldReturnNonNullStream"> <source>Resource stream provider should return non-null stream.</source> <target state="translated">资源流提供程序应返回非空流。</target> <note /> </trans-unit> <trans-unit id="ReferenceResolverShouldReturnReadableNonNullStream"> <source>Reference resolver should return readable non-null stream.</source> <target state="translated">引用解析程序应返回非空的可读流。</target> <note /> </trans-unit> <trans-unit id="EmptyOrInvalidResourceName"> <source>Empty or invalid resource name</source> <target state="translated">空的或无效的资源名</target> <note /> </trans-unit> <trans-unit id="EmptyOrInvalidFileName"> <source>Empty or invalid file name</source> <target state="translated">空的或无效的文件名</target> <note /> </trans-unit> <trans-unit id="ResourceDataProviderShouldReturnNonNullStream"> <source>Resource data provider should return non-null stream</source> <target state="translated">资源数据提供程序应返回非空流</target> <note /> </trans-unit> <trans-unit id="FileNotFound"> <source>File not found.</source> <target state="translated">未找到文件。</target> <note /> </trans-unit> <trans-unit id="PathReturnedByResolveStrongNameKeyFileMustBeAbsolute"> <source>Path returned by {0}.ResolveStrongNameKeyFile must be absolute: '{1}'</source> <target state="translated">由 {0}.ResolveStrongNameKeyFile 返回的路径必须是绝对路径:“{1}”</target> <note /> </trans-unit> <trans-unit id="TypeMustBeASubclassOfSyntaxAnnotation"> <source>type must be a subclass of SyntaxAnnotation.</source> <target state="translated">类型必须是 SyntaxAnnotation 的子类。</target> <note /> </trans-unit> <trans-unit id="InvalidModuleName"> <source>Invalid module name specified in metadata module '{0}': '{1}'</source> <target state="translated">在元数据模块“{0}”中所指定的模块名称无效:“{1}”</target> <note /> </trans-unit> <trans-unit id="FileSizeExceedsMaximumAllowed"> <source>File size exceeds maximum allowed size of a valid metadata file.</source> <target state="translated">文件大小超过有效元数据文件所允许的最大大小。</target> <note /> </trans-unit> <trans-unit id="NameCannotBeNull"> <source>Name cannot be null.</source> <target state="translated">名称不能为 null。</target> <note /> </trans-unit> <trans-unit id="NameCannotBeEmpty"> <source>Name cannot be empty.</source> <target state="translated">名称不能为空。</target> <note /> </trans-unit> <trans-unit id="NameCannotStartWithWhitespace"> <source>Name cannot start with whitespace.</source> <target state="translated">名称不能以空格开头。</target> <note /> </trans-unit> <trans-unit id="NameContainsInvalidCharacter"> <source>Name contains invalid characters.</source> <target state="translated">名称包含无效字符。</target> <note /> </trans-unit> <trans-unit id="SpanDoesNotIncludeStartOfLine"> <source>The span does not include the start of a line.</source> <target state="translated">范围不包括行的开头。</target> <note /> </trans-unit> <trans-unit id="SpanDoesNotIncludeEndOfLine"> <source>The span does not include the end of a line.</source> <target state="translated">范围不包括行的末尾。</target> <note /> </trans-unit> <trans-unit id="StartMustNotBeNegative"> <source>'start' must not be negative</source> <target state="translated">'“开始”不能为负</target> <note /> </trans-unit> <trans-unit id="EndMustNotBeLessThanStart"> <source>'end' must not be less than 'start'</source> <target state="translated">'“结束时间”不得早于“开始时间”</target> <note /> </trans-unit> <trans-unit id="InvalidContentType"> <source>Invalid content type</source> <target state="translated">无效的内容类型</target> <note /> </trans-unit> <trans-unit id="ExpectedNonEmptyPublicKey"> <source>Expected non-empty public key</source> <target state="translated">预期的非空公钥</target> <note /> </trans-unit> <trans-unit id="InvalidSizeOfPublicKeyToken"> <source>Invalid size of public key token.</source> <target state="translated">公钥标记的大小无效。</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyName"> <source>Invalid characters in assembly name</source> <target state="translated">程序集名称中有无效字符</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyCultureName"> <source>Invalid characters in assembly culture name</source> <target state="translated">程序集区域性名称中有无效字符</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportReadAndSeek"> <source>Stream must support read and seek operations.</source> <target state="translated">流必须支持读取和搜寻操作。</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportRead"> <source>Stream must be readable.</source> <target state="translated">流必须为可读。</target> <note /> </trans-unit> <trans-unit id="StreamMustSupportWrite"> <source>Stream must be writable.</source> <target state="translated">流必须是可写的。</target> <note /> </trans-unit> <trans-unit id="PdbStreamUnexpectedWhenEmbedding"> <source>PDB stream should not be given when embedding PDB into the PE stream.</source> <target state="translated">将 PE 流嵌入 PDB 时,无法提供 PDB 流。</target> <note /> </trans-unit> <trans-unit id="PdbStreamUnexpectedWhenEmittingMetadataOnly"> <source>PDB stream should not be given when emitting metadata only.</source> <target state="translated">仅发出元数据时不应提供 PDB 流。</target> <note /> </trans-unit> <trans-unit id="MetadataPeStreamUnexpectedWhenEmittingMetadataOnly"> <source>Metadata PE stream should not be given when emitting metadata only.</source> <target state="translated">仅发出元数据时不应提供元数据 PE 流。</target> <note /> </trans-unit> <trans-unit id="IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream"> <source>Including private members should not be used when emitting to the secondary assembly output.</source> <target state="translated">发出到辅助程序集输出时不应包含私有成员。</target> <note /> </trans-unit> <trans-unit id="MustIncludePrivateMembersUnlessRefAssembly"> <source>Must include private members unless emitting a ref assembly.</source> <target state="translated">必须包括私有成员,除非发出 ref 程序集。</target> <note /> </trans-unit> <trans-unit id="EmbeddingPdbUnexpectedWhenEmittingMetadata"> <source>Embedding PDB is not allowed when emitting metadata.</source> <target state="translated">不允许在发出元数据时嵌入 PDB。</target> <note /> </trans-unit> <trans-unit id="CannotTargetNetModuleWhenEmittingRefAssembly"> <source>Cannot target net module when emitting ref assembly.</source> <target state="translated">无法在发出引用程序集时将 Net 模块作为目标。</target> <note /> </trans-unit> <trans-unit id="InvalidHash"> <source>Invalid hash.</source> <target state="translated">哈希无效。</target> <note /> </trans-unit> <trans-unit id="UnsupportedHashAlgorithm"> <source>Unsupported hash algorithm.</source> <target state="translated">不支持的哈希算法。</target> <note /> </trans-unit> <trans-unit id="InconsistentLanguageVersions"> <source>Inconsistent language versions</source> <target state="translated">不一致的语言版本</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidRelocation"> <source>Win32 resources, assumed to be in COFF object format, have one or more invalid relocation header values.</source> <target state="translated">Win32 资源,假定为 COFF 对象格式,具有一个或多个无效的重定位标头值。</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidSectionSize"> <source>Win32 resources, assumed to be in COFF object format, have an invalid section size.</source> <target state="translated">Win32 资源,假定为 COFF 对象格式,具有一个无效的节大小。</target> <note /> </trans-unit> <trans-unit id="CoffResourceInvalidSymbol"> <source>Win32 resources, assumed to be in COFF object format, have one or more invalid symbol values.</source> <target state="translated">Win32 资源,假定为 COFF 对象格式,具有一个或多个无效的符号值。</target> <note /> </trans-unit> <trans-unit id="CoffResourceMissingSection"> <source>Win32 resources, assumed to be in COFF object format, are missing one or both of sections '.rsrc$01' and '.rsrc$02'</source> <target state="translated">Win32 资源,假定为 COFF 对象格式,缺少其中一个或全部两个节:“.rsrc$01” 和“.rsrc$02”</target> <note /> </trans-unit> <trans-unit id="IconStreamUnexpectedFormat"> <source>Icon stream is not in the expected format.</source> <target state="translated">图标流不是预期格式。</target> <note /> </trans-unit> <trans-unit id="InvalidCultureName"> <source>Invalid culture name: '{0}'</source> <target state="translated">无效的区域性名称:“{0}”</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidGlobalSectionName"> <source>Global analyzer config section name '{0}' is invalid as it is not an absolute path. Section will be ignored. Section was declared in file: '{1}'</source> <target state="translated">全局分析器配置部分名称“{0}”无效,因为它不是绝对路径。部分将被忽略。部分已在以下文件中声明:“{1}”。</target> <note>{0}: invalid section name, {1} path to global config</note> </trans-unit> <trans-unit id="WRN_InvalidGlobalSectionName_Title"> <source>Global analyzer config section name is invalid as it is not an absolute path. Section will be ignored.</source> <target state="translated">全局分析器配置部分名称无效,因为它不是绝对路径。部分将被忽略。</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSeverityInAnalyzerConfig"> <source>The diagnostic '{0}' was given an invalid severity '{1}' in the analyzer config file at '{2}'.</source> <target state="translated">在 "{2}" 的分析器配置文件中为诊断 "{0}" 给定了无效的严重性 "{1}"。</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSeverityInAnalyzerConfig_Title"> <source>Invalid severity in analyzer config file.</source> <target state="translated">分析器配置文件中的严重性无效。</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleGlobalAnalyzerKeys"> <source>Multiple global analyzer config files set the same key '{0}' in section '{1}'. It has been unset. Key was set by the following files: '{2}'</source> <target state="translated">多个全局分析器配置文件在“{1}”部分中设置了相同的密钥“{0}”。它已取消设置。密钥由以下文件设置:“{2}”</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleGlobalAnalyzerKeys_Title"> <source>Multiple global analyzer config files set the same key. It has been unset.</source> <target state="translated">多个全局分析器配置文件设置了相同的密钥。它已取消设置。</target> <note /> </trans-unit> <trans-unit id="WinRTIdentityCantBeRetargetable"> <source>WindowsRuntime identity can't be retargetable</source> <target state="translated">WindowsRuntime 标识不可重定目标</target> <note /> </trans-unit> <trans-unit id="PEImageNotAvailable"> <source>PE image not available.</source> <target state="translated">PE 映像不可用。</target> <note /> </trans-unit> <trans-unit id="AssemblySigningNotSupported"> <source>Assembly signing not supported.</source> <target state="translated">不支持程序集签名。</target> <note /> </trans-unit> <trans-unit id="XmlReferencesNotSupported"> <source>References to XML documents are not supported.</source> <target state="translated">不支持 XML 文档的引用。</target> <note /> </trans-unit> <trans-unit id="FailedToResolveRuleSetName"> <source>Could not locate the rule set file '{0}'.</source> <target state="translated">未能找到规则集文件“{0}”。</target> <note /> </trans-unit> <trans-unit id="InvalidRuleSetInclude"> <source>An error occurred while loading the included rule set file {0} - {1}</source> <target state="translated">加载所含规则集文件 {0} - {1} 时出错</target> <note /> </trans-unit> <trans-unit id="CompilerAnalyzerFailure"> <source>Analyzer Failure</source> <target state="translated">分析器故障</target> <note>{0}: Analyzer name {1}: Type name {2}: Localized exception message {3}: Localized detail message</note> </trans-unit> <trans-unit id="CompilerAnalyzerThrows"> <source>Analyzer '{0}' threw an exception of type '{1}' with message '{2}'. {3}</source> <target state="translated">分析器“{0}”引发类型为“{1}”的异常,并显示消息“{2}”。 {3}</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverFailure"> <source>Analyzer Driver Failure</source> <target state="translated">分析器驱动程序故障</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverThrows"> <source>Analyzer driver threw an exception of type '{0}' with message '{1}'.</source> <target state="translated">分析器驱动程序抛出类型为“{0}”的异常,并显示消息“{1}”。</target> <note /> </trans-unit> <trans-unit id="AnalyzerDriverThrowsDescription"> <source>Analyzer driver threw the following exception: '{0}'.</source> <target state="translated">分析器驱动程序抛出以下异常: “{0}”。</target> <note /> </trans-unit> <trans-unit id="PEImageDoesntContainManagedMetadata"> <source>PE image doesn't contain managed metadata.</source> <target state="translated">PE 映像不包含任何托管元数据。</target> <note /> </trans-unit> <trans-unit id="ChangesMustNotOverlap"> <source>The changes must not overlap.</source> <target state="translated">更改必须有序且不重叠。</target> <note /> </trans-unit> <trans-unit id="DiagnosticIdCantBeNullOrWhitespace"> <source>A DiagnosticDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space.</source> <target state="translated">DiagnosticDescriptor 必须有一个 ID,该 ID 不能为 null、空字符串或只包含空格的字符串。</target> <note /> </trans-unit> <trans-unit id="RuleSetHasDuplicateRules"> <source>The rule set file has duplicate rules for '{0}' with differing actions '{1}' and '{2}'.</source> <target state="translated">规则集文件对有不同操作 “{1}” 和“{2}”的“{0}”有重复规则。</target> <note /> </trans-unit> <trans-unit id="CantCreateModuleReferenceToAssembly"> <source>Can't create a module reference to an assembly.</source> <target state="translated">无法对程序集创建模块引用.</target> <note /> </trans-unit> <trans-unit id="CantCreateReferenceToDynamicAssembly"> <source>Can't create a metadata reference to a dynamic assembly.</source> <target state="translated">无法对动态程序集创建元数据引用。</target> <note /> </trans-unit> <trans-unit id="CantCreateReferenceToAssemblyWithoutLocation"> <source>Can't create a metadata reference to an assembly without location.</source> <target state="translated">无法对不含位置的程序集创建元数据引用。</target> <note /> </trans-unit> <trans-unit id="ArgumentCannotBeEmpty"> <source>Argument cannot be empty.</source> <target state="translated">参数不能为空。</target> <note /> </trans-unit> <trans-unit id="ArgumentElementCannotBeNull"> <source>Argument cannot have a null element.</source> <target state="translated">参数不能具有 null 元素。</target> <note /> </trans-unit> <trans-unit id="UnsupportedDiagnosticReported"> <source>Reported diagnostic with ID '{0}' is not supported by the analyzer.</source> <target state="translated">分析器不支持 ID 为“{0}”的报告的诊断。</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticIdReported"> <source>Reported diagnostic has an ID '{0}', which is not a valid identifier.</source> <target state="translated">报告的诊断 ID“{0}”不是有效的标识符。</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticLocationReported"> <source>Reported diagnostic '{0}' has a source location in file '{1}', which is not part of the compilation being analyzed.</source> <target state="translated">报告的诊断“{0}”的源位置位于文件“{1}”中,后者不是要分析的编译的一部分。</target> <note /> </trans-unit> <trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder"> <source>The type '{0}' is not understood by the serialization binder.</source> <target state="translated">序列化绑定器不理解“{0}”类型。</target> <note /> </trans-unit> <trans-unit id="Cannot_deserialize_type_0"> <source>Cannot deserialize type '{0}'.</source> <target state="translated">无法反序列化类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="Cannot_serialize_type_0"> <source>Cannot serialize type '{0}'.</source> <target state="translated">无法序列化类型“{0}”。</target> <note /> </trans-unit> <trans-unit id="InvalidNodeToTrack"> <source>Node to track is not a descendant of the root.</source> <target state="translated">要跟踪的节点不是根的后代。</target> <note /> </trans-unit> <trans-unit id="NodeOrTokenOutOfSequence"> <source>A node or token is out of sequence.</source> <target state="translated">某个节点或标记的顺序不正确。</target> <note /> </trans-unit> <trans-unit id="UnexpectedTypeOfNodeInList"> <source>A node in the list is not of the expected type.</source> <target state="translated">列表中的某个节点不是预期的类型。</target> <note /> </trans-unit> <trans-unit id="MissingListItem"> <source>The item specified is not the element of a list.</source> <target state="translated">指定的项不是列表的元素。</target> <note /> </trans-unit> <trans-unit id="InvalidPublicKey"> <source>Invalid public key.</source> <target state="translated">公钥无效</target> <note /> </trans-unit> <trans-unit id="InvalidPublicKeyToken"> <source>Invalid public key token.</source> <target state="translated">公钥标记无效。</target> <note /> </trans-unit> <trans-unit id="InvalidDataAtOffset"> <source>Invalid data at offset {0}: {1}{2}*{3}{4}</source> <target state="translated">偏移量 {0} 处的数据无效: {1}{2}*{3}{4}</target> <note /> </trans-unit> <trans-unit id="SymWriterNotDeterministic"> <source>Windows PDB writer doesn't support deterministic compilation: '{0}'</source> <target state="translated">Windows PDB 编写器不支持确定性的编译:“{0}”</target> <note /> </trans-unit> <trans-unit id="SymWriterOlderVersionThanRequired"> <source>The version of Windows PDB writer is older than required: '{0}'</source> <target state="translated">Windows PDB 编写器的版本早于要求的版本:“{0}”</target> <note /> </trans-unit> <trans-unit id="SymWriterDoesNotSupportSourceLink"> <source>Windows PDB writer doesn't support SourceLink feature: '{0}'</source> <target state="translated">Windows PDB 编写器不支持 SourceLink 功能:“{0}”</target> <note /> </trans-unit> <trans-unit id="RuleSetBadAttributeValue"> <source>The attribute {0} has an invalid value of {1}.</source> <target state="translated">属性 {0} 具有无效值 {1}。</target> <note /> </trans-unit> <trans-unit id="RuleSetMissingAttribute"> <source>The element {0} is missing an attribute named {1}.</source> <target state="translated">元素 {0} 缺少名为 {1} 的属性。</target> <note /> </trans-unit> <trans-unit id="KeepAliveIsNotAnInteger"> <source>Argument to '/keepalive' option is not a 32-bit integer.</source> <target state="translated">"/keepalive" 选项的参数不是一个 32 位整数。</target> <note /> </trans-unit> <trans-unit id="KeepAliveIsTooSmall"> <source>Arguments to '/keepalive' option below -1 are invalid.</source> <target state="translated">小于 -1 的 "/keepalive" 选项的参数无效。</target> <note /> </trans-unit> <trans-unit id="KeepAliveWithoutShared"> <source>'/keepalive' option is only valid with '/shared' option.</source> <target state="translated">'"/keepalive" 选项仅在与 "/shared" 选项一起使用时有效。</target> <note /> </trans-unit> <trans-unit id="MismatchedVersion"> <source>Roslyn compiler server reports different protocol version than build task.</source> <target state="translated">Roslyn 编译器服务器报告不同于生成任务的协议版本。</target> <note /> </trans-unit> <trans-unit id="MissingKeepAlive"> <source>Missing argument for '/keepalive' option.</source> <target state="translated">缺少 "/keepalive" 选项的参数。</target> <note /> </trans-unit> <trans-unit id="AnalyzerTotalExecutionTime"> <source>Total analyzer execution time: {0} seconds.</source> <target state="translated">分析器总执行时间: {0} 秒。</target> <note /> </trans-unit> <trans-unit id="MultithreadedAnalyzerExecutionNote"> <source>NOTE: Elapsed time may be less than analyzer execution time because analyzers can run concurrently.</source> <target state="translated">注意: 运行时间可能小于分析器执行时间,因为分析器可以同时运行。</target> <note /> </trans-unit> <trans-unit id="AnalyzerExecutionTimeColumnHeader"> <source>Time (s)</source> <target state="translated">时间(秒)</target> <note /> </trans-unit> <trans-unit id="AnalyzerNameColumnHeader"> <source>Analyzer</source> <target state="translated">分析器</target> <note /> </trans-unit> <trans-unit id="NoAnalyzersFound"> <source>No analyzers found</source> <target state="translated">找不到分析器</target> <note /> </trans-unit> <trans-unit id="DuplicateAnalyzerInstances"> <source>Argument contains duplicate analyzer instances.</source> <target state="translated">参数包含重复的分析器实例。</target> <note /> </trans-unit> <trans-unit id="UnsupportedAnalyzerInstance"> <source>Argument contains an analyzer instance that does not belong to the 'Analyzers' for this CompilationWithAnalyzers instance.</source> <target state="translated">参数包含的分析器实例不属于此 CompilationWithAnalyzers 实例的“Analyzers”。</target> <note /> </trans-unit> <trans-unit id="InvalidTree"> <source>Syntax tree doesn't belong to the underlying 'Compilation'.</source> <target state="translated">语法树不属于底层“Compilation”。</target> <note /> </trans-unit> <trans-unit id="ResourceStreamEndedUnexpectedly"> <source>Resource stream ended at {0} bytes, expected {1} bytes.</source> <target state="translated">资源流在 {0} 字节结束,预期为 {1} 字节。</target> <note /> </trans-unit> <trans-unit id="SharedArgumentMissing"> <source>Value for argument '/shared:' must not be empty</source> <target state="translated">参数“/shared:”的值不能为空</target> <note /> </trans-unit> <trans-unit id="ExceptionContext"> <source>Exception occurred with following context: {0}</source> <target state="translated">出现异常,上下文如下: {0}</target> <note /> </trans-unit> <trans-unit id="AnonymousTypeMemberAndNamesCountMismatch2"> <source>{0} and {1} must have the same length.</source> <target state="translated">{0} 和 {1} 长度必须相同。</target> <note /> </trans-unit> <trans-unit id="AnonymousTypeArgumentCountMismatch2"> <source>{0} must either be 'default' or have the same length as {1}.</source> <target state="translated">{0} 必须为“默认值”或具有与 {1} 相同的长度。</target> <note /> </trans-unit> <trans-unit id="InconsistentSyntaxTreeFeature"> <source>Inconsistent syntax tree features</source> <target state="translated">不一致的语法树特征</target> <note /> </trans-unit> <trans-unit id="ReferenceOfTypeIsInvalid1"> <source>Reference of type '{0}' is not valid for this compilation.</source> <target state="translated">引用类型“{0}”对该编译无效。</target> <note /> </trans-unit> <trans-unit id="MetadataRefNotFoundToRemove1"> <source>MetadataReference '{0}' not found to remove.</source> <target state="translated">未找到要删除的 MetadataReference“{0}”。</target> <note /> </trans-unit> <trans-unit id="TupleElementNameCountMismatch"> <source>If tuple element names are specified, the number of element names must match the cardinality of the tuple.</source> <target state="translated">如果指定了元组元素名称,元素名称的数量必须与元组基数相匹配。</target> <note /> </trans-unit> <trans-unit id="TupleElementNameEmpty"> <source>Tuple element name cannot be an empty string.</source> <target state="translated">元组元素名称不能为空字符串。</target> <note /> </trans-unit> <trans-unit id="TupleElementLocationCountMismatch"> <source>If tuple element locations are specified, the number of locations must match the cardinality of the tuple.</source> <target state="translated">如果已指定元组元素位置,则位置的数量必须与元组基数相匹配。</target> <note /> </trans-unit> <trans-unit id="TuplesNeedAtLeastTwoElements"> <source>Tuples must have at least two elements.</source> <target state="translated">元组必须包含至少两个元素。</target> <note /> </trans-unit> <trans-unit id="CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion"> <source>The compilation references multiple assemblies whose versions only differ in auto-generated build and/or revision numbers.</source> <target state="translated">编译将引用多个程序集(其版本只在自动生成的版本和/或修订号方面有所不同)。</target> <note /> </trans-unit> <trans-unit id="TupleUnderlyingTypeMustBeTupleCompatible"> <source>The underlying type for a tuple must be tuple-compatible.</source> <target state="translated">元组的基础类型必须符合元组。</target> <note /> </trans-unit> <trans-unit id="UnrecognizedResourceFileFormat"> <source>Unrecognized resource file format.</source> <target state="translated">无法识别的资源文件格式。</target> <note /> </trans-unit> <trans-unit id="SourceTextCannotBeEmbedded"> <source>SourceText cannot be embedded. Provide encoding or canBeEmbedded=true at construction.</source> <target state="translated">不能嵌入 SourceText。在构造时提供编码或 canBeEmbedded=true。</target> <note /> </trans-unit> <trans-unit id="StreamIsTooLong"> <source>Stream is too long.</source> <target state="translated">“流”过长。</target> <note /> </trans-unit> <trans-unit id="EmbeddedTextsRequirePdb"> <source>Embedded texts are only supported when emitting a PDB.</source> <target state="translated">仅在发出 PDB 时才支持嵌入的文本。</target> <note /> </trans-unit> <trans-unit id="TheStreamCannotBeWrittenTo"> <source>The stream cannot be written to.</source> <target state="translated">无法向流中写入。</target> <note /> </trans-unit> <trans-unit id="ElementIsExpected"> <source>element is expected</source> <target state="translated">应为元素</target> <note /> </trans-unit> <trans-unit id="SeparatorIsExpected"> <source>separator is expected</source> <target state="translated">需要分隔符</target> <note /> </trans-unit> <trans-unit id="TheStreamCannotBeReadFrom"> <source>The stream cannot be read from.</source> <target state="translated">无法从流中读取。</target> <note /> </trans-unit> <trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values"> <source>Deserialization reader for '{0}' read incorrect number of values.</source> <target state="translated">“{0}”的反序列化读取器读取到错误数量的值。</target> <note /> </trans-unit> <trans-unit id="Stream_contains_invalid_data"> <source>Stream contains invalid data</source> <target state="translated">流包含无效的数据</target> <note /> </trans-unit> <trans-unit id="InvalidDiagnosticSpanReported"> <source>Reported diagnostic '{0}' has a source location '{1}' in file '{2}', which is outside of the given file.</source> <target state="translated">报告的诊断“{0}”的源位置“{1}”位于文件“{2}”中,后者不是给定文件。</target> <note /> </trans-unit> <trans-unit id="ExceptionEnablingMulticoreJit"> <source>Warning: Could not enable multicore JIT due to exception: {0}.</source> <target state="translated">警告: 无法启用 multicore JIT,因为存在异常: {0}。</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./docs/wiki/Getting-Started-VB-Syntax-Analysis.md
## Prerequisites * [Visual Studio 2015](https://www.visualstudio.com/downloads) * [.NET Compiler Platform SDK](https://aka.ms/roslynsdktemplates) ## Introduction Today, the Visual Basic and C# compilers are black boxes - text goes in and bytes come out - with no transparency into the intermediate phases of the compilation pipeline. With the **.NET Compiler Platform** (formerly known as "Roslyn"), tools and developers can leverage the exact same data structures and algorithms the compiler uses to analyze and understand code with confidence that that information is accurate and complete. In this walkthrough we'll explore the **Syntax API**. The **Syntax API** exposes the parsers, the syntax trees themselves, and utilities for reasoning about and constructing them. ## Understanding Syntax Trees The **Syntax API** exposes the syntax trees the compilers use to understand Visual Basic and C# programs. They are produced by the same parser that runs when a project is built or a developer hits F5. The syntax trees have full-fidelity with the language; every bit of information in a code file is represented in the tree, including things like comments or whitespace. Writing a syntax tree to text will reproduce the exact original text that was parsed. The syntax trees are also immutable; once created a syntax tree can never be changed. This means consumers of the trees can analyze the trees on multiple threads, without locks or other concurrency measures, with the security that the data will never change. The four primary building blocks of syntax trees are: * The **SyntaxTree** class, an instance of which represents an entire parse tree. **SyntaxTree** is an abstract class which has language-specific derivatives. To parse syntax in a particular language you will need to use the parse methods on the **VisualBasicSyntaxTree** (or **CSharpSyntaxTree**) class. * The **SyntaxNode** class, instances of which represent syntactic constructs such as declarations, statements, clauses, and expressions. * The **SyntaxToken** structure, which represents an individual keyword, identifier, operator, or punctuation. * And lastly the **SyntaxTrivia** structure, which represents syntactically insignificant bits of information such as the whitespace between tokens, preprocessing directives, and comments. **SyntaxNodes** are composed hierarchically to form a tree that completely represents everything in a fragment of Visual Basic or C# code. For example, were you to examine the following Visual Basic source file using the Syntax Visualizer (In Visual Studio, choose **View -> Other Windows -> Syntax Visualizer**) it tree view would look like this: **SyntaxNode**: Blue | **SyntaxToken**: Green | **SyntaxTrivia**: Red ![Visual Basic Code File](images/walkthrough-vb-syntax-figure1.png) By navigating this tree structure you can find any statement, expression, token, or bit of whitespace in a code file! ## Traversing Trees ### Manual Traversal The following steps use **Edit and Continue** to demonstrate how to parse VB source text and find a parameter declaration contained in the source. #### Example - Manually traversing the tree 1) Create a new Visual Basic **Stand-Alone Code Analysis Tool** project. * In Visual Studio, choose **File -> New -> Project...** to display the New Project dialog. * Under **Visual Basic -> Extensibility**, choose **Stand-Alone Code Analysis Tool**. * Name your project "**GettingStartedVB**" and click OK. 2) Enter the following line at the top of your **Module1.vb** file: ```VB.NET Option Strict Off ``` * Some readers may run with **Option Strict** turned **On** by default at the project level. Turning **Option Strict** **Off** in this walkthrough simplifies many of the examples by removing much of the casting required. 3) Enter the following code into your **Main** method: ```VB.NET Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections Imports System.Linq Imports System.Text Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() ``` 4) Move your cursor to the line containing the **End Sub** of your **Main** method and set a breakpoint there. * In Visual Studio, choose **Debug -> Toggle Breakpoint**. 5) Run the program. * In Visual Studio, choose **Debug -> Start Debugging**. 6) Inspect the root variable in the debugger by hovering over it and expanding the datatip. * Note that its **Imports** property is a collection with four elements; one for each Import statement in the parsed text. * Note that the **KindText** of the root node is **CompilationUnit**. * Note that the **Members** collection of the **CompilationUnitSyntax** node has one element. 7) Insert the following statement at the end of the Main method to store the first member of the root **CompilationUnitSyntax** variable into a new variable: ```VB.NET Dim firstMember = root.Members(0) ``` 8) Set this statement as the next statement to be executed and execute it. * Right-click this line and choose **Set Next Statement**. * In Visual Studio, choose **Debug -> Step Over**, to execute this statement and initialize the new variable. * You will need to repeat this process for each of the following steps as we introduce new variables and inspect them with the debugger. 9) Hover over the **firstMember** variable and expand the datatips to inspect it. * Note that its **KindText** is **NamespaceBlock**. * Note that its run-time type is actually **NamespaceBlockSyntax**. 10) Cast this node to **NamespaceBlockSyntax** and store it in a new variable: ```VB.NET Dim helloWorldDeclaration As Syntax.NamespaceBlockSyntax = firstMember ``` 11) Execute this statement and examine the **helloWorldDeclaration** variable. * Note that like the **CompilationUnitSyntax**, **NamespaceBlockSyntax** also has a **Members** collection. 12) Examine the **Members** collection. * Note that it contains a single member. Examine it. * Note that its **KindText** is **ModuleBlock.** * Note that its run-time type is **ModuleBlockSyntax**. 13) Cast this node to **ModuleBlockSyntax** and store it in a new variable: ```VB.NET Dim programDeclaration As Syntax.ModuleBlockSyntax = helloWorldDeclaration.Members(0) ``` 14) Execute this statement. 15) Locate the **Main** declaration in the **programDeclaration.Members** collection and store it in a new variable: ```VB.NET Dim mainDeclaration As Syntax.MethodBlockSyntax = programDeclaration.Members(0) ``` 16) Execute this statement and examine the members of the **MethodBlockSyntax** object. * Examine the **BlockStatement** property. * Note the **AsClause**, and **Identifier** properties. * Note the **ParameterList** property; examine it. * Note that it contains both the open and close parentheses of the parameter list in addition to the list of parameters themselves. * Note that the parameters are stored as a **SeparatedSyntaxList**(**Of** **ParameterSyntax**). * Note the **Statements** property. 17) Store the first parameter of the **Main** declaration in a variable. ```VB.NET Dim argsParameter As Syntax.ParameterSyntax = mainDeclaration.BlockStatement.ParameterList.Parameters(0) ``` 18) Execute this statement and examine the **argsParameter** variable. * Examine the **Identifier** property; note that it is of type **ModifiedIdentifierSyntax**. This type represents a normal identifier with an optional nullable modifier (**x?**) and/or array rank specifier (**arr(,)**). * Note that a **ModifiedIdentifierSyntax** has an **Identifier** property of the structure type **SyntaxToken**. * Examine the properties of the **Identifier** **SyntaxToken**; note that the text of the identifier can be found in the **ValueText** property. 19) Stop the program. * In Visual Studio, choose **Debug -> Stop Debugging**. 20) Your program should look like this now: ```VB.NET Option Strict Off Module Module1 Sub Main() Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections Imports System.Linq Imports System.Text Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() Dim firstMember = root.Members(0) Dim helloWorldDeclaration As Syntax.NamespaceBlockSyntax = firstMember Dim programDeclaration As Syntax.ModuleBlockSyntax = helloWorldDeclaration.Members(0) Dim mainDeclaration As Syntax.MethodBlockSyntax = programDeclaration.Members(0) Dim argsParameter As Syntax.ParameterSyntax = mainDeclaration.BlockStatement.ParameterList.Parameters(0) End Sub End Module ``` ### Query Methods In addition to traversing trees using the properties of the **SyntaxNode** derived classes you can also explore the syntax tree using the query methods defined on **SyntaxNode**. These methods should be immediately familiar to anyone familiar with XPath. You can use these methods with LINQ to quickly find things in a tree. #### Example - Using query methods 1) Using IntelliSense, examine the members of the **SyntaxNode** class through the root variable. * Note query methods such as **DescendantNodes**, **AncestorsAndSelf**, and **ChildNodes**. 2) Add the following statements to the end of the **Main** method. The first statement uses a LINQ expression and the **DescendantNodes** method to locate the same parameter as in the previous example: ```VB.NET Dim firstParameters = From methodStatement In root.DescendantNodes(). OfType(Of Syntax.MethodStatementSyntax)() Where methodStatement.Identifier.ValueText = "Main" Select methodStatement.ParameterList.Parameters.First() Dim argsParameter2 = firstParameters.First() ``` 3) Start debugging the program. 4) Open the Immediate Window. * In Visual Studio, choose **Debug -> Windows -> Immediate**. 5) Using the Immediate window, type the expression **? argsParameter Is argsParameter2** and press enter to evaluate it. * Note that the LINQ expression found the same parameter as manually navigating the tree. 6) Stop the program. ### SyntaxWalkers Often you'll want to find all nodes of a specific type in a syntax tree, for example, every property declaration in a file. By extending the **VisualBasicSyntaxWalker** class and overriding the **VisitPropertyStatement** method, you can process every property declaration in a syntax tree without knowing its structure beforehand. **VisualBasicSyntaxWalker** is a specific kind of **SyntaxVisitor** which recursively visits a node and each of its children. #### Example - Implementing a VisualBasicSyntaxWalker This example shows how to implement a **VisualBasicSyntaxWalker** which examines an entire syntax tree and collects any **Imports** statements it finds which aren't importing a **System** namespace. 1) Create a new Visual Basic **Stand-Alone Code Analysis Tool** project; name it "**ImportsCollectorVB**". 3) Enter the following line at the top of your **Module1.vb** file: ```VB.NET Option Strict Off ``` 3) Enter the following code into your **Main** method: ```VB.NET Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports Microsoft.VisualBasic Imports System Imports System.Collections Imports Microsoft.Win32 Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis Imports System.ComponentModel Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() ``` 4) Note that this source text contains a long list of **Imports** statements. 5) Add a new class file to the project. * In Visual Studio, choose **Project -> Add Class...** * In the "Add New Item" dialog type **ImportsCollector.vb** as the filename. 6) Enter the following lines at the top of your **ImportsCollector.vb** file: ```VB.NET Option Strict Off ``` 7) Make the new **ImportsCollector** class in this file extend the **VisualBasicSyntaxWalker** class: ```VB.NET Public Class ImportsCollector Inherits VisualBasicSyntaxWalker ``` 8) Declare a public read-only field in the **ImportsCollector** class; we'll use this variable to store the **ImportsStatementSyntax** nodes we find: ```VB.NET Public ReadOnly [Imports] As New List(Of Syntax.ImportsStatementSyntax)() ``` 9) Override the **VisitSimpleImportsClause** method: ```VB.NET Public Overrides Sub VisitSimpleImportsClause( node As SimpleImportsClauseSyntax ) End Sub ``` 10) Using IntelliSense, examine the **SimpleImportsClauseSyntax** class through the **node** parameter of this method. * Note the **Name** property of type **NameSyntax**; this stores the name of the namespace being imported. 11) Replace the code in the **VisitSimpleImportsClause** method with the following to conditionally add the found **node** to the **[Imports]** collection if **Name** doesn't refer to the **System** namespace or any of its descendant namespaces: ```VB.NET If node.Name.ToString() = "System" OrElse node.Name.ToString().StartsWith("System.") Then Return [Imports].Add(node.Parent) ``` 12) The **ImportsCollector.vb** file should now look like this: ```VB.NET Option Strict Off Public Class ImportsCollector Inherits VisualBasicSyntaxWalker Public ReadOnly [Imports] As New List(Of Syntax.ImportsStatementSyntax)() Public Overrides Sub VisitSimpleImportsClause( node As SimpleImportsClauseSyntax ) If node.Name.ToString() = "System" OrElse node.Name.ToString().StartsWith("System.") Then Return [Imports].Add(node.Parent) End Sub End Class ``` 13) Return to the **Module1.vb** file. 14) Add the following code to the end of the **Main** method to create an instance of the **ImportsCollector**, use that instance to visit the root of the parsed tree, and iterate over the **ImportsStatementSyntax** nodes collected and print their names to the **Console**: ```VB.NET Dim visitor As New ImportsCollector() visitor.Visit(root) For Each statement In visitor.Imports Console.WriteLine(statement) Next ``` 15) Your **Module1.vb** file should now look like this: ```VB.NET Option Strict Off Module Module1 Sub Main() Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports Microsoft.VisualBasic Imports System Imports System.Collections Imports Microsoft.Win32 Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis Imports System.ComponentModel Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() Dim visitor As New ImportsCollector() visitor.Visit(root) For Each statement In visitor.Imports Console.WriteLine(statement) Next End Sub End Module ``` 16) Press **Ctrl+F5** to run the program without debugging it. You should see the following output: ``` Imports Microsoft.VisualBasic Imports Microsoft.Win32 Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Press any key to continue . . . ``` 17) Observe that the walker has located all four non-**System** namespace **Imports** statements. 18) Congratulations! You've just used the **Syntax API** to locate specific kinds of VB statements and declarations in VB source code.
## Prerequisites * [Visual Studio 2015](https://www.visualstudio.com/downloads) * [.NET Compiler Platform SDK](https://aka.ms/roslynsdktemplates) ## Introduction Today, the Visual Basic and C# compilers are black boxes - text goes in and bytes come out - with no transparency into the intermediate phases of the compilation pipeline. With the **.NET Compiler Platform** (formerly known as "Roslyn"), tools and developers can leverage the exact same data structures and algorithms the compiler uses to analyze and understand code with confidence that that information is accurate and complete. In this walkthrough we'll explore the **Syntax API**. The **Syntax API** exposes the parsers, the syntax trees themselves, and utilities for reasoning about and constructing them. ## Understanding Syntax Trees The **Syntax API** exposes the syntax trees the compilers use to understand Visual Basic and C# programs. They are produced by the same parser that runs when a project is built or a developer hits F5. The syntax trees have full-fidelity with the language; every bit of information in a code file is represented in the tree, including things like comments or whitespace. Writing a syntax tree to text will reproduce the exact original text that was parsed. The syntax trees are also immutable; once created a syntax tree can never be changed. This means consumers of the trees can analyze the trees on multiple threads, without locks or other concurrency measures, with the security that the data will never change. The four primary building blocks of syntax trees are: * The **SyntaxTree** class, an instance of which represents an entire parse tree. **SyntaxTree** is an abstract class which has language-specific derivatives. To parse syntax in a particular language you will need to use the parse methods on the **VisualBasicSyntaxTree** (or **CSharpSyntaxTree**) class. * The **SyntaxNode** class, instances of which represent syntactic constructs such as declarations, statements, clauses, and expressions. * The **SyntaxToken** structure, which represents an individual keyword, identifier, operator, or punctuation. * And lastly the **SyntaxTrivia** structure, which represents syntactically insignificant bits of information such as the whitespace between tokens, preprocessing directives, and comments. **SyntaxNodes** are composed hierarchically to form a tree that completely represents everything in a fragment of Visual Basic or C# code. For example, were you to examine the following Visual Basic source file using the Syntax Visualizer (In Visual Studio, choose **View -> Other Windows -> Syntax Visualizer**) it tree view would look like this: **SyntaxNode**: Blue | **SyntaxToken**: Green | **SyntaxTrivia**: Red ![Visual Basic Code File](images/walkthrough-vb-syntax-figure1.png) By navigating this tree structure you can find any statement, expression, token, or bit of whitespace in a code file! ## Traversing Trees ### Manual Traversal The following steps use **Edit and Continue** to demonstrate how to parse VB source text and find a parameter declaration contained in the source. #### Example - Manually traversing the tree 1) Create a new Visual Basic **Stand-Alone Code Analysis Tool** project. * In Visual Studio, choose **File -> New -> Project...** to display the New Project dialog. * Under **Visual Basic -> Extensibility**, choose **Stand-Alone Code Analysis Tool**. * Name your project "**GettingStartedVB**" and click OK. 2) Enter the following line at the top of your **Module1.vb** file: ```VB.NET Option Strict Off ``` * Some readers may run with **Option Strict** turned **On** by default at the project level. Turning **Option Strict** **Off** in this walkthrough simplifies many of the examples by removing much of the casting required. 3) Enter the following code into your **Main** method: ```VB.NET Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections Imports System.Linq Imports System.Text Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() ``` 4) Move your cursor to the line containing the **End Sub** of your **Main** method and set a breakpoint there. * In Visual Studio, choose **Debug -> Toggle Breakpoint**. 5) Run the program. * In Visual Studio, choose **Debug -> Start Debugging**. 6) Inspect the root variable in the debugger by hovering over it and expanding the datatip. * Note that its **Imports** property is a collection with four elements; one for each Import statement in the parsed text. * Note that the **KindText** of the root node is **CompilationUnit**. * Note that the **Members** collection of the **CompilationUnitSyntax** node has one element. 7) Insert the following statement at the end of the Main method to store the first member of the root **CompilationUnitSyntax** variable into a new variable: ```VB.NET Dim firstMember = root.Members(0) ``` 8) Set this statement as the next statement to be executed and execute it. * Right-click this line and choose **Set Next Statement**. * In Visual Studio, choose **Debug -> Step Over**, to execute this statement and initialize the new variable. * You will need to repeat this process for each of the following steps as we introduce new variables and inspect them with the debugger. 9) Hover over the **firstMember** variable and expand the datatips to inspect it. * Note that its **KindText** is **NamespaceBlock**. * Note that its run-time type is actually **NamespaceBlockSyntax**. 10) Cast this node to **NamespaceBlockSyntax** and store it in a new variable: ```VB.NET Dim helloWorldDeclaration As Syntax.NamespaceBlockSyntax = firstMember ``` 11) Execute this statement and examine the **helloWorldDeclaration** variable. * Note that like the **CompilationUnitSyntax**, **NamespaceBlockSyntax** also has a **Members** collection. 12) Examine the **Members** collection. * Note that it contains a single member. Examine it. * Note that its **KindText** is **ModuleBlock.** * Note that its run-time type is **ModuleBlockSyntax**. 13) Cast this node to **ModuleBlockSyntax** and store it in a new variable: ```VB.NET Dim programDeclaration As Syntax.ModuleBlockSyntax = helloWorldDeclaration.Members(0) ``` 14) Execute this statement. 15) Locate the **Main** declaration in the **programDeclaration.Members** collection and store it in a new variable: ```VB.NET Dim mainDeclaration As Syntax.MethodBlockSyntax = programDeclaration.Members(0) ``` 16) Execute this statement and examine the members of the **MethodBlockSyntax** object. * Examine the **BlockStatement** property. * Note the **AsClause**, and **Identifier** properties. * Note the **ParameterList** property; examine it. * Note that it contains both the open and close parentheses of the parameter list in addition to the list of parameters themselves. * Note that the parameters are stored as a **SeparatedSyntaxList**(**Of** **ParameterSyntax**). * Note the **Statements** property. 17) Store the first parameter of the **Main** declaration in a variable. ```VB.NET Dim argsParameter As Syntax.ParameterSyntax = mainDeclaration.BlockStatement.ParameterList.Parameters(0) ``` 18) Execute this statement and examine the **argsParameter** variable. * Examine the **Identifier** property; note that it is of type **ModifiedIdentifierSyntax**. This type represents a normal identifier with an optional nullable modifier (**x?**) and/or array rank specifier (**arr(,)**). * Note that a **ModifiedIdentifierSyntax** has an **Identifier** property of the structure type **SyntaxToken**. * Examine the properties of the **Identifier** **SyntaxToken**; note that the text of the identifier can be found in the **ValueText** property. 19) Stop the program. * In Visual Studio, choose **Debug -> Stop Debugging**. 20) Your program should look like this now: ```VB.NET Option Strict Off Module Module1 Sub Main() Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports System Imports System.Collections Imports System.Linq Imports System.Text Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() Dim firstMember = root.Members(0) Dim helloWorldDeclaration As Syntax.NamespaceBlockSyntax = firstMember Dim programDeclaration As Syntax.ModuleBlockSyntax = helloWorldDeclaration.Members(0) Dim mainDeclaration As Syntax.MethodBlockSyntax = programDeclaration.Members(0) Dim argsParameter As Syntax.ParameterSyntax = mainDeclaration.BlockStatement.ParameterList.Parameters(0) End Sub End Module ``` ### Query Methods In addition to traversing trees using the properties of the **SyntaxNode** derived classes you can also explore the syntax tree using the query methods defined on **SyntaxNode**. These methods should be immediately familiar to anyone familiar with XPath. You can use these methods with LINQ to quickly find things in a tree. #### Example - Using query methods 1) Using IntelliSense, examine the members of the **SyntaxNode** class through the root variable. * Note query methods such as **DescendantNodes**, **AncestorsAndSelf**, and **ChildNodes**. 2) Add the following statements to the end of the **Main** method. The first statement uses a LINQ expression and the **DescendantNodes** method to locate the same parameter as in the previous example: ```VB.NET Dim firstParameters = From methodStatement In root.DescendantNodes(). OfType(Of Syntax.MethodStatementSyntax)() Where methodStatement.Identifier.ValueText = "Main" Select methodStatement.ParameterList.Parameters.First() Dim argsParameter2 = firstParameters.First() ``` 3) Start debugging the program. 4) Open the Immediate Window. * In Visual Studio, choose **Debug -> Windows -> Immediate**. 5) Using the Immediate window, type the expression **? argsParameter Is argsParameter2** and press enter to evaluate it. * Note that the LINQ expression found the same parameter as manually navigating the tree. 6) Stop the program. ### SyntaxWalkers Often you'll want to find all nodes of a specific type in a syntax tree, for example, every property declaration in a file. By extending the **VisualBasicSyntaxWalker** class and overriding the **VisitPropertyStatement** method, you can process every property declaration in a syntax tree without knowing its structure beforehand. **VisualBasicSyntaxWalker** is a specific kind of **SyntaxVisitor** which recursively visits a node and each of its children. #### Example - Implementing a VisualBasicSyntaxWalker This example shows how to implement a **VisualBasicSyntaxWalker** which examines an entire syntax tree and collects any **Imports** statements it finds which aren't importing a **System** namespace. 1) Create a new Visual Basic **Stand-Alone Code Analysis Tool** project; name it "**ImportsCollectorVB**". 3) Enter the following line at the top of your **Module1.vb** file: ```VB.NET Option Strict Off ``` 3) Enter the following code into your **Main** method: ```VB.NET Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports Microsoft.VisualBasic Imports System Imports System.Collections Imports Microsoft.Win32 Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis Imports System.ComponentModel Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() ``` 4) Note that this source text contains a long list of **Imports** statements. 5) Add a new class file to the project. * In Visual Studio, choose **Project -> Add Class...** * In the "Add New Item" dialog type **ImportsCollector.vb** as the filename. 6) Enter the following lines at the top of your **ImportsCollector.vb** file: ```VB.NET Option Strict Off ``` 7) Make the new **ImportsCollector** class in this file extend the **VisualBasicSyntaxWalker** class: ```VB.NET Public Class ImportsCollector Inherits VisualBasicSyntaxWalker ``` 8) Declare a public read-only field in the **ImportsCollector** class; we'll use this variable to store the **ImportsStatementSyntax** nodes we find: ```VB.NET Public ReadOnly [Imports] As New List(Of Syntax.ImportsStatementSyntax)() ``` 9) Override the **VisitSimpleImportsClause** method: ```VB.NET Public Overrides Sub VisitSimpleImportsClause( node As SimpleImportsClauseSyntax ) End Sub ``` 10) Using IntelliSense, examine the **SimpleImportsClauseSyntax** class through the **node** parameter of this method. * Note the **Name** property of type **NameSyntax**; this stores the name of the namespace being imported. 11) Replace the code in the **VisitSimpleImportsClause** method with the following to conditionally add the found **node** to the **[Imports]** collection if **Name** doesn't refer to the **System** namespace or any of its descendant namespaces: ```VB.NET If node.Name.ToString() = "System" OrElse node.Name.ToString().StartsWith("System.") Then Return [Imports].Add(node.Parent) ``` 12) The **ImportsCollector.vb** file should now look like this: ```VB.NET Option Strict Off Public Class ImportsCollector Inherits VisualBasicSyntaxWalker Public ReadOnly [Imports] As New List(Of Syntax.ImportsStatementSyntax)() Public Overrides Sub VisitSimpleImportsClause( node As SimpleImportsClauseSyntax ) If node.Name.ToString() = "System" OrElse node.Name.ToString().StartsWith("System.") Then Return [Imports].Add(node.Parent) End Sub End Class ``` 13) Return to the **Module1.vb** file. 14) Add the following code to the end of the **Main** method to create an instance of the **ImportsCollector**, use that instance to visit the root of the parsed tree, and iterate over the **ImportsStatementSyntax** nodes collected and print their names to the **Console**: ```VB.NET Dim visitor As New ImportsCollector() visitor.Visit(root) For Each statement In visitor.Imports Console.WriteLine(statement) Next ``` 15) Your **Module1.vb** file should now look like this: ```VB.NET Option Strict Off Module Module1 Sub Main() Dim tree As SyntaxTree = VisualBasicSyntaxTree.ParseText( "Imports Microsoft.VisualBasic Imports System Imports System.Collections Imports Microsoft.Win32 Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis Imports System.ComponentModel Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic Namespace HelloWorld Module Program Sub Main(args As String()) Console.WriteLine(""Hello, World!"") End Sub End Module End Namespace") Dim root As Syntax.CompilationUnitSyntax = tree.GetRoot() Dim visitor As New ImportsCollector() visitor.Visit(root) For Each statement In visitor.Imports Console.WriteLine(statement) Next End Sub End Module ``` 16) Press **Ctrl+F5** to run the program without debugging it. You should see the following output: ``` Imports Microsoft.VisualBasic Imports Microsoft.Win32 Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Press any key to continue . . . ``` 17) Observe that the walker has located all four non-**System** namespace **Imports** statements. 18) Congratulations! You've just used the **Syntax API** to locate specific kinds of VB statements and declarations in VB source code.
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/LanguageServer/ProtocolUnitTests/ProjectContext/GetTextDocumentWithContextHandlerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.ProjectContext { public class GetTextDocumentWithContextHandlerTests : AbstractLanguageServerProtocolTests { [Fact] public async Task SingleDocumentReturnsSingleContext() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj""> <Document FilePath = ""C:\C.cs"">{|caret:|}</Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var documentUri = locations["caret"].Single().Uri; var result = await RunGetProjectContext(testLspServer, documentUri); Assert.NotNull(result); Assert.Equal(0, result!.DefaultIndex); var context = Assert.Single(result.ProjectContexts); Assert.Equal(ProtocolConversions.ProjectIdToProjectContextId(testLspServer.GetCurrentSolution().ProjectIds.Single()), context.Id); Assert.Equal(LSP.ProjectContextKind.CSharp, context.Kind); Assert.Equal("CSProj", context.Label); } [Fact] public async Task MultipleDocumentsReturnsMultipleContexts() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{|caret:|}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1"">{|caret:|}</Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var documentUri = locations["caret"].Single().Uri; var result = await RunGetProjectContext(testLspServer, documentUri); Assert.NotNull(result); Assert.Collection(result!.ProjectContexts.OrderBy(c => c.Label), c => Assert.Equal("CSProj1", c.Label), c => Assert.Equal("CSProj2", c.Label)); } [Fact] public async Task SwitchingContextsChangesDefaultContext() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{|caret:|}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1""></Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); // Ensure the documents are open so we can change contexts foreach (var document in testLspServer.TestWorkspace.Documents) { _ = document.GetOpenTextContainer(); } var documentUri = locations["caret"].Single().Uri; foreach (var project in testLspServer.GetCurrentSolution().Projects) { testLspServer.TestWorkspace.SetDocumentContext(project.DocumentIds.Single()); var result = await RunGetProjectContext(testLspServer, documentUri); Assert.Equal(ProtocolConversions.ProjectIdToProjectContextId(project.Id), result!.ProjectContexts[result.DefaultIndex].Id); Assert.Equal(project.Name, result!.ProjectContexts[result.DefaultIndex].Label); } } private static async Task<LSP.ActiveProjectContexts?> RunGetProjectContext(TestLspServer testLspServer, Uri uri) { return await testLspServer.ExecuteRequestAsync<LSP.GetTextDocumentWithContextParams, LSP.ActiveProjectContexts?>(LSP.MSLSPMethods.ProjectContextsName, CreateGetProjectContextParams(uri), new LSP.ClientCapabilities(), clientName: null, cancellationToken: CancellationToken.None); } private static LSP.GetTextDocumentWithContextParams CreateGetProjectContextParams(Uri uri) => new LSP.GetTextDocumentWithContextParams() { TextDocument = new LSP.TextDocumentItem { Uri = uri } }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.ProjectContext { public class GetTextDocumentWithContextHandlerTests : AbstractLanguageServerProtocolTests { [Fact] public async Task SingleDocumentReturnsSingleContext() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj""> <Document FilePath = ""C:\C.cs"">{|caret:|}</Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var documentUri = locations["caret"].Single().Uri; var result = await RunGetProjectContext(testLspServer, documentUri); Assert.NotNull(result); Assert.Equal(0, result!.DefaultIndex); var context = Assert.Single(result.ProjectContexts); Assert.Equal(ProtocolConversions.ProjectIdToProjectContextId(testLspServer.GetCurrentSolution().ProjectIds.Single()), context.Id); Assert.Equal(LSP.ProjectContextKind.CSharp, context.Kind); Assert.Equal("CSProj", context.Label); } [Fact] public async Task MultipleDocumentsReturnsMultipleContexts() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{|caret:|}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1"">{|caret:|}</Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var documentUri = locations["caret"].Single().Uri; var result = await RunGetProjectContext(testLspServer, documentUri); Assert.NotNull(result); Assert.Collection(result!.ProjectContexts.OrderBy(c => c.Label), c => Assert.Equal("CSProj1", c.Label), c => Assert.Equal("CSProj2", c.Label)); } [Fact] public async Task SwitchingContextsChangesDefaultContext() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{|caret:|}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1""></Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); // Ensure the documents are open so we can change contexts foreach (var document in testLspServer.TestWorkspace.Documents) { _ = document.GetOpenTextContainer(); } var documentUri = locations["caret"].Single().Uri; foreach (var project in testLspServer.GetCurrentSolution().Projects) { testLspServer.TestWorkspace.SetDocumentContext(project.DocumentIds.Single()); var result = await RunGetProjectContext(testLspServer, documentUri); Assert.Equal(ProtocolConversions.ProjectIdToProjectContextId(project.Id), result!.ProjectContexts[result.DefaultIndex].Id); Assert.Equal(project.Name, result!.ProjectContexts[result.DefaultIndex].Label); } } private static async Task<LSP.ActiveProjectContexts?> RunGetProjectContext(TestLspServer testLspServer, Uri uri) { return await testLspServer.ExecuteRequestAsync<LSP.GetTextDocumentWithContextParams, LSP.ActiveProjectContexts?>(LSP.MSLSPMethods.ProjectContextsName, CreateGetProjectContextParams(uri), new LSP.ClientCapabilities(), clientName: null, cancellationToken: CancellationToken.None); } private static LSP.GetTextDocumentWithContextParams CreateGetProjectContextParams(Uri uri) => new LSP.GetTextDocumentWithContextParams() { TextDocument = new LSP.TextDocumentItem { Uri = uri } }; } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/Core/Portable/GenerateMember/GenerateConstructor/GenerateConstructorHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal static class GenerateConstructorHelpers { public static bool CanDelegateTo<TExpressionSyntax>( SemanticDocument document, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, IMethodSymbol constructor) where TExpressionSyntax : SyntaxNode { // Look for constructors in this specified type that are: // 1. Accessible. We obviously need our constructor to be able to call that other constructor. // 2. Won't cause a cycle. i.e. if we're generating a new constructor from an existing constructor, // then we don't want it calling back into us. // 3. Are compatible with the parameters we're generating for this constructor. Compatible means there // exists an implicit conversion from the new constructor's parameter types to the existing // constructor's parameter types. var semanticFacts = document.Document.GetRequiredLanguageService<ISemanticFactsService>(); var semanticModel = document.SemanticModel; var compilation = semanticModel.Compilation; return constructor.Parameters.Length == parameters.Length && constructor.Parameters.SequenceEqual(parameters, (p1, p2) => p1.RefKind == p2.RefKind) && IsSymbolAccessible(compilation, constructor) && IsCompatible(semanticFacts, semanticModel, constructor, expressions); } private static bool IsSymbolAccessible(Compilation compilation, ISymbol symbol) { if (symbol == null) return false; if (symbol is IPropertySymbol { SetMethod: { } setMethod } property && !IsSymbolAccessible(compilation, setMethod)) { return false; } // Public and protected constructors are accessible. Internal constructors are // accessible if we have friend access. We can't call the normal accessibility // checkers since they will think that a protected constructor isn't accessible // (since we don't have the destination type that would have access to them yet). switch (symbol.DeclaredAccessibility) { case Accessibility.ProtectedOrInternal: case Accessibility.Protected: case Accessibility.Public: return true; case Accessibility.ProtectedAndInternal: case Accessibility.Internal: return compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(symbol.ContainingAssembly); default: return false; } } private static bool IsCompatible<TExpressionSyntax>( ISemanticFactsService semanticFacts, SemanticModel semanticModel, IMethodSymbol constructor, ImmutableArray<TExpressionSyntax?> expressions) where TExpressionSyntax : SyntaxNode { Debug.Assert(constructor.Parameters.Length == expressions.Length); // Resolve the constructor into our semantic model's compilation; if the constructor we're looking at is from // another project with a different language. var constructorInCompilation = (IMethodSymbol?)SymbolKey.Create(constructor).Resolve(semanticModel.Compilation).Symbol; if (constructorInCompilation == null) { // If the constructor can't be mapped into our invocation project, we'll just bail. // Note the logic in this method doesn't handle a complicated case where: // // 1. Project A has some public type. // 2. Project B references A, and has one constructor that uses the public type from A. // 3. Project C, which references B but not A, has an invocation of B's constructor passing some // parameters. // // The algorithm of this class tries to map the constructor in B (that we might delegate to) into // C, but that constructor might not be mappable if the public type from A is not available. // However, theoretically the public type from A could have a user-defined conversion. // The alternative approach might be to map the type of the parameters back into B, and then // classify the conversions in Project B, but that'll run into other issues if the experssions // don't have a natural type (like default). We choose to ignore all complicated cases here. return false; } for (var i = 0; i < constructorInCompilation.Parameters.Length; i++) { var constructorParameter = constructorInCompilation.Parameters[i]; if (constructorParameter == null) return false; // In VB the argument may not have been specified at all if the parameter is optional if (expressions[i] is null && constructorParameter.IsOptional) continue; var conversion = semanticFacts.ClassifyConversion(semanticModel, expressions[i], constructorParameter.Type); if (!conversion.IsIdentity && !conversion.IsImplicit) return false; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal static class GenerateConstructorHelpers { public static bool CanDelegateTo<TExpressionSyntax>( SemanticDocument document, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, IMethodSymbol constructor) where TExpressionSyntax : SyntaxNode { // Look for constructors in this specified type that are: // 1. Accessible. We obviously need our constructor to be able to call that other constructor. // 2. Won't cause a cycle. i.e. if we're generating a new constructor from an existing constructor, // then we don't want it calling back into us. // 3. Are compatible with the parameters we're generating for this constructor. Compatible means there // exists an implicit conversion from the new constructor's parameter types to the existing // constructor's parameter types. var semanticFacts = document.Document.GetRequiredLanguageService<ISemanticFactsService>(); var semanticModel = document.SemanticModel; var compilation = semanticModel.Compilation; return constructor.Parameters.Length == parameters.Length && constructor.Parameters.SequenceEqual(parameters, (p1, p2) => p1.RefKind == p2.RefKind) && IsSymbolAccessible(compilation, constructor) && IsCompatible(semanticFacts, semanticModel, constructor, expressions); } private static bool IsSymbolAccessible(Compilation compilation, ISymbol symbol) { if (symbol == null) return false; if (symbol is IPropertySymbol { SetMethod: { } setMethod } property && !IsSymbolAccessible(compilation, setMethod)) { return false; } // Public and protected constructors are accessible. Internal constructors are // accessible if we have friend access. We can't call the normal accessibility // checkers since they will think that a protected constructor isn't accessible // (since we don't have the destination type that would have access to them yet). switch (symbol.DeclaredAccessibility) { case Accessibility.ProtectedOrInternal: case Accessibility.Protected: case Accessibility.Public: return true; case Accessibility.ProtectedAndInternal: case Accessibility.Internal: return compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(symbol.ContainingAssembly); default: return false; } } private static bool IsCompatible<TExpressionSyntax>( ISemanticFactsService semanticFacts, SemanticModel semanticModel, IMethodSymbol constructor, ImmutableArray<TExpressionSyntax?> expressions) where TExpressionSyntax : SyntaxNode { Debug.Assert(constructor.Parameters.Length == expressions.Length); // Resolve the constructor into our semantic model's compilation; if the constructor we're looking at is from // another project with a different language. var constructorInCompilation = (IMethodSymbol?)SymbolKey.Create(constructor).Resolve(semanticModel.Compilation).Symbol; if (constructorInCompilation == null) { // If the constructor can't be mapped into our invocation project, we'll just bail. // Note the logic in this method doesn't handle a complicated case where: // // 1. Project A has some public type. // 2. Project B references A, and has one constructor that uses the public type from A. // 3. Project C, which references B but not A, has an invocation of B's constructor passing some // parameters. // // The algorithm of this class tries to map the constructor in B (that we might delegate to) into // C, but that constructor might not be mappable if the public type from A is not available. // However, theoretically the public type from A could have a user-defined conversion. // The alternative approach might be to map the type of the parameters back into B, and then // classify the conversions in Project B, but that'll run into other issues if the experssions // don't have a natural type (like default). We choose to ignore all complicated cases here. return false; } for (var i = 0; i < constructorInCompilation.Parameters.Length; i++) { var constructorParameter = constructorInCompilation.Parameters[i]; if (constructorParameter == null) return false; // In VB the argument may not have been specified at all if the parameter is optional if (expressions[i] is null && constructorParameter.IsOptional) continue; var conversion = semanticFacts.ClassifyConversion(semanticModel, expressions[i], constructorParameter.Type); if (!conversion.IsIdentity && !conversion.IsImplicit) return false; } return true; } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractAggregatedFormattingResult.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 Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract class AbstractAggregatedFormattingResult : IFormattingResult { protected readonly SyntaxNode Node; private readonly IList<AbstractFormattingResult> _formattingResults; private readonly SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? _formattingSpans; private readonly CancellableLazy<IList<TextChange>> _lazyTextChanges; private readonly CancellableLazy<SyntaxNode> _lazyNode; public AbstractAggregatedFormattingResult( SyntaxNode node, IList<AbstractFormattingResult> formattingResults, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans) { Contract.ThrowIfNull(node); Contract.ThrowIfNull(formattingResults); this.Node = node; _formattingResults = formattingResults; _formattingSpans = formattingSpans; _lazyTextChanges = new CancellableLazy<IList<TextChange>>(CreateTextChanges); _lazyNode = new CancellableLazy<SyntaxNode>(CreateFormattedRoot); } /// <summary> /// rewrite the node with the given trivia information in the map /// </summary> protected abstract SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> changeMap, CancellationToken cancellationToken); protected SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector> GetFormattingSpans() => _formattingSpans ?? SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), _formattingResults.Select(r => r.FormattedSpan)); #region IFormattingResult implementation public bool ContainsChanges { get { return this.GetTextChanges(CancellationToken.None).Count > 0; } } public IList<TextChange> GetTextChanges(CancellationToken cancellationToken) => _lazyTextChanges.GetValue(cancellationToken); public SyntaxNode GetFormattedRoot(CancellationToken cancellationToken) => _lazyNode.GetValue(cancellationToken); private IList<TextChange> CreateTextChanges(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_AggregateCreateTextChanges, cancellationToken)) { // quick check var changes = CreateTextChangesWorker(cancellationToken); // formatted spans and formatting spans are different, filter returns to formatting span return _formattingSpans == null ? changes : changes.Where(s => _formattingSpans.HasIntervalThatIntersectsWith(s.Span)).ToList(); } } private IList<TextChange> CreateTextChangesWorker(CancellationToken cancellationToken) { if (_formattingResults.Count == 1) { return _formattingResults[0].GetTextChanges(cancellationToken); } // pre-allocate list var count = _formattingResults.Sum(r => r.GetTextChanges(cancellationToken).Count); var result = new List<TextChange>(count); foreach (var formattingResult in _formattingResults) { result.AddRange(formattingResult.GetTextChanges(cancellationToken)); } return result; } private SyntaxNode CreateFormattedRoot(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_AggregateCreateFormattedRoot, cancellationToken)) { // create a map var map = new Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData>(); _formattingResults.Do(result => result.GetChanges(cancellationToken).Do(change => map.Add(change.Item1, change.Item2))); return Rewriter(map, cancellationToken); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract class AbstractAggregatedFormattingResult : IFormattingResult { protected readonly SyntaxNode Node; private readonly IList<AbstractFormattingResult> _formattingResults; private readonly SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? _formattingSpans; private readonly CancellableLazy<IList<TextChange>> _lazyTextChanges; private readonly CancellableLazy<SyntaxNode> _lazyNode; public AbstractAggregatedFormattingResult( SyntaxNode node, IList<AbstractFormattingResult> formattingResults, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans) { Contract.ThrowIfNull(node); Contract.ThrowIfNull(formattingResults); this.Node = node; _formattingResults = formattingResults; _formattingSpans = formattingSpans; _lazyTextChanges = new CancellableLazy<IList<TextChange>>(CreateTextChanges); _lazyNode = new CancellableLazy<SyntaxNode>(CreateFormattedRoot); } /// <summary> /// rewrite the node with the given trivia information in the map /// </summary> protected abstract SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> changeMap, CancellationToken cancellationToken); protected SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector> GetFormattingSpans() => _formattingSpans ?? SimpleIntervalTree.Create(new TextSpanIntervalIntrospector(), _formattingResults.Select(r => r.FormattedSpan)); #region IFormattingResult implementation public bool ContainsChanges { get { return this.GetTextChanges(CancellationToken.None).Count > 0; } } public IList<TextChange> GetTextChanges(CancellationToken cancellationToken) => _lazyTextChanges.GetValue(cancellationToken); public SyntaxNode GetFormattedRoot(CancellationToken cancellationToken) => _lazyNode.GetValue(cancellationToken); private IList<TextChange> CreateTextChanges(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_AggregateCreateTextChanges, cancellationToken)) { // quick check var changes = CreateTextChangesWorker(cancellationToken); // formatted spans and formatting spans are different, filter returns to formatting span return _formattingSpans == null ? changes : changes.Where(s => _formattingSpans.HasIntervalThatIntersectsWith(s.Span)).ToList(); } } private IList<TextChange> CreateTextChangesWorker(CancellationToken cancellationToken) { if (_formattingResults.Count == 1) { return _formattingResults[0].GetTextChanges(cancellationToken); } // pre-allocate list var count = _formattingResults.Sum(r => r.GetTextChanges(cancellationToken).Count); var result = new List<TextChange>(count); foreach (var formattingResult in _formattingResults) { result.AddRange(formattingResult.GetTextChanges(cancellationToken)); } return result; } private SyntaxNode CreateFormattedRoot(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Formatting_AggregateCreateFormattedRoot, cancellationToken)) { // create a map var map = new Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData>(); _formattingResults.Do(result => result.GetChanges(cancellationToken).Do(change => map.Add(change.Item1, change.Item2))); return Rewriter(map, cancellationToken); } } #endregion } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Def/ValueTracking/ComputingTreeViewItem.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.Windows.Threading; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class ComputingTreeViewItem : TreeViewItemBase { public string Text => ServicesVSResources.Calculating; public ComputingTreeViewItem() { } } }
// Licensed to the .NET Foundation under one or more 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.Windows.Threading; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class ComputingTreeViewItem : TreeViewItemBase { public string Text => ServicesVSResources.Calculating; public ComputingTreeViewItem() { } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Workspaces/VisualBasic/Portable/PublicAPI.Unshipped.txt
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Portable/LanguageVersion.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Specifies the language version. /// </summary> public enum LanguageVersion { /// <summary> /// C# language version 1 /// </summary> CSharp1 = 1, /// <summary> /// C# language version 2 /// </summary> CSharp2 = 2, /// <summary> /// C# language version 3 /// </summary> /// <remarks> /// Features: LINQ. /// </remarks> CSharp3 = 3, /// <summary> /// C# language version 4 /// </summary> /// <remarks> /// Features: dynamic. /// </remarks> CSharp4 = 4, /// <summary> /// C# language version 5 /// </summary> /// <remarks> /// Features: async, caller info attributes. /// </remarks> CSharp5 = 5, /// <summary> /// C# language version 6 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Using of a static class</description></item> /// <item><description>Exception filters</description></item> /// <item><description>Await in catch/finally blocks</description></item> /// <item><description>Auto-property initializers</description></item> /// <item><description>Expression-bodied methods and properties</description></item> /// <item><description>Null-propagating operator ?.</description></item> /// <item><description>String interpolation</description></item> /// <item><description>nameof operator</description></item> /// <item><description>Dictionary initializer</description></item> /// </list> /// </remarks> CSharp6 = 6, /// <summary> /// C# language version 7.0 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Out variables</description></item> /// <item><description>Pattern-matching</description></item> /// <item><description>Tuples</description></item> /// <item><description>Deconstruction</description></item> /// <item><description>Discards</description></item> /// <item><description>Local functions</description></item> /// <item><description>Digit separators</description></item> /// <item><description>Ref returns and locals</description></item> /// <item><description>Generalized async return types</description></item> /// <item><description>More expression-bodied members</description></item> /// <item><description>Throw expressions</description></item> /// </list> /// </remarks> CSharp7 = 7, /// <summary> /// C# language version 7.1 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Async Main</description></item> /// <item><description>Default literal</description></item> /// <item><description>Inferred tuple element names</description></item> /// <item><description>Pattern-matching with generics</description></item> /// </list> /// </remarks> CSharp7_1 = 701, /// <summary> /// C# language version 7.2 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Ref readonly</description></item> /// <item><description>Ref and readonly structs</description></item> /// <item><description>Ref extensions</description></item> /// <item><description>Conditional ref operator</description></item> /// <item><description>Private protected</description></item> /// <item><description>Digit separators after base specifier</description></item> /// <item><description>Non-trailing named arguments</description></item> /// </list> /// </remarks> CSharp7_2 = 702, /// <summary> /// C# language version 7.3 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Indexing fixed fields does not require pinning</description></item> /// <item><description>ref local variables may be reassigned</description></item> /// <item><description>stackalloc arrays support initializers</description></item> /// <item><description>More types support the fixed statement</description></item> /// <item><description>Enhanced generic constraints</description></item> /// <item><description>Tuples support == and !=</description></item> /// <item><description>Attach attributes to the backing fields for auto-implemented properties</description></item> /// <item><description>Method overload resolution improvements when arguments differ by 'in'</description></item> /// <item><description>Extend expression variables in initializers</description></item> /// <item><description>Improved overload candidates</description></item> /// <item><description>New compiler options (-publicsign and -pathmap)</description></item> /// </list> /// </remarks> CSharp7_3 = 703, /// <summary> /// C# language version 8.0 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Readonly members</description></item> /// <item><description>Default interface methods</description></item> /// <item><description>Pattern matching enhancements (switch expressions, property patterns, tuple patterns, and positional patterns)</description></item> /// <item><description>Using declarations</description></item> /// <item><description>Static local functions</description></item> /// <item><description>Disposable ref structs</description></item> /// <item><description>Nullable reference types</description></item> /// <item><description>Asynchronous streams</description></item> /// <item><description>Asynchronous disposable</description></item> /// <item><description>Indices and ranges</description></item> /// <item><description>Null-coalescing assignment</description></item> /// <item><description>Unmanaged constructed types</description></item> /// <item><description>Stackalloc in nested expressions</description></item> /// <item><description>Enhancement of interpolated verbatim strings</description></item> /// </list> /// </remarks> CSharp8 = 800, /// <summary> /// C# language version 9.0 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Records</description></item> /// <item><description>Init only setters</description></item> /// <item><description>Top-level statements</description></item> /// <item><description>Pattern matching enhancements</description></item> /// <item><description>Native sized integers</description></item> /// <item><description>Function pointers</description></item> /// <item><description>Suppress emitting localsinit flag</description></item> /// <item><description>Target-typed new expressions</description></item> /// <item><description>Static anonymous functions</description></item> /// <item><description>Target-typed conditional expressions</description></item> /// <item><description>Covariant return types</description></item> /// <item><description>Extension GetEnumerator support for foreach loops</description></item> /// <item><description>Lambda discard parameters</description></item> /// <item><description>Attributes on local functions</description></item> /// <item><description>Module initializers</description></item> /// <item><description>New features for partial methods</description></item> /// </list> /// </remarks> CSharp9 = 900, /// <summary> /// C# language version 10.0 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Record structs</description></item> /// <item><description>Global using directives</description></item> /// <item><description>Lambda improvements</description></item> /// <item><description>Improved definite assignment</description></item> /// <item><description>Constant interpolated strings</description></item> /// <item><description>Mix declarations and variables in deconstruction</description></item> /// <item><description>Extended property patterns</description></item> /// <item><description>Sealed record ToString</description></item> /// <item><description>Source Generator v2 APIs</description></item> /// <item><description>Method-level AsyncMethodBuilder</description></item> /// </list> /// </remarks> CSharp10 = 1000, /// <summary> /// The latest major supported version. /// </summary> LatestMajor = int.MaxValue - 2, /// <summary> /// Preview of the next language version. /// </summary> Preview = int.MaxValue - 1, /// <summary> /// The latest supported version of the language. /// </summary> Latest = int.MaxValue, /// <summary> /// The default language version, which is the latest supported version. /// </summary> Default = 0, } internal static class LanguageVersionExtensionsInternal { internal static bool IsValid(this LanguageVersion value) { switch (value) { case LanguageVersion.CSharp1: case LanguageVersion.CSharp2: case LanguageVersion.CSharp3: case LanguageVersion.CSharp4: case LanguageVersion.CSharp5: case LanguageVersion.CSharp6: case LanguageVersion.CSharp7: case LanguageVersion.CSharp7_1: case LanguageVersion.CSharp7_2: case LanguageVersion.CSharp7_3: case LanguageVersion.CSharp8: case LanguageVersion.CSharp9: case LanguageVersion.CSharp10: case LanguageVersion.Preview: return true; } return false; } internal static ErrorCode GetErrorCode(this LanguageVersion version) { switch (version) { case LanguageVersion.CSharp1: return ErrorCode.ERR_FeatureNotAvailableInVersion1; case LanguageVersion.CSharp2: return ErrorCode.ERR_FeatureNotAvailableInVersion2; case LanguageVersion.CSharp3: return ErrorCode.ERR_FeatureNotAvailableInVersion3; case LanguageVersion.CSharp4: return ErrorCode.ERR_FeatureNotAvailableInVersion4; case LanguageVersion.CSharp5: return ErrorCode.ERR_FeatureNotAvailableInVersion5; case LanguageVersion.CSharp6: return ErrorCode.ERR_FeatureNotAvailableInVersion6; case LanguageVersion.CSharp7: return ErrorCode.ERR_FeatureNotAvailableInVersion7; case LanguageVersion.CSharp7_1: return ErrorCode.ERR_FeatureNotAvailableInVersion7_1; case LanguageVersion.CSharp7_2: return ErrorCode.ERR_FeatureNotAvailableInVersion7_2; case LanguageVersion.CSharp7_3: return ErrorCode.ERR_FeatureNotAvailableInVersion7_3; case LanguageVersion.CSharp8: return ErrorCode.ERR_FeatureNotAvailableInVersion8; case LanguageVersion.CSharp9: return ErrorCode.ERR_FeatureNotAvailableInVersion9; case LanguageVersion.CSharp10: return ErrorCode.ERR_FeatureNotAvailableInVersion10; default: throw ExceptionUtilities.UnexpectedValue(version); } } } internal class CSharpRequiredLanguageVersion : RequiredLanguageVersion { internal LanguageVersion Version { get; } internal CSharpRequiredLanguageVersion(LanguageVersion version) { Version = version; } public override string ToString() => Version.ToDisplayString(); } public static class LanguageVersionFacts { /// <summary> /// Usages of TestOptions.RegularNext and LanguageVersionFacts.CSharpNext /// will be replaced with TestOptions.RegularN and LanguageVersion.CSharpN when language version N is introduced. /// </summary> internal const LanguageVersion CSharpNext = LanguageVersion.Preview; /// <summary> /// Displays the version number in the format expected on the command-line (/langver flag). /// For instance, "6", "7.0", "7.1", "latest". /// </summary> public static string ToDisplayString(this LanguageVersion version) { switch (version) { case LanguageVersion.CSharp1: return "1"; case LanguageVersion.CSharp2: return "2"; case LanguageVersion.CSharp3: return "3"; case LanguageVersion.CSharp4: return "4"; case LanguageVersion.CSharp5: return "5"; case LanguageVersion.CSharp6: return "6"; case LanguageVersion.CSharp7: return "7.0"; case LanguageVersion.CSharp7_1: return "7.1"; case LanguageVersion.CSharp7_2: return "7.2"; case LanguageVersion.CSharp7_3: return "7.3"; case LanguageVersion.CSharp8: return "8.0"; case LanguageVersion.CSharp9: return "9.0"; case LanguageVersion.CSharp10: return "10.0"; case LanguageVersion.Default: return "default"; case LanguageVersion.Latest: return "latest"; case LanguageVersion.LatestMajor: return "latestmajor"; case LanguageVersion.Preview: return "preview"; default: throw ExceptionUtilities.UnexpectedValue(version); } } /// <summary> /// Try parse a <see cref="LanguageVersion"/> from a string input, returning default if input was null. /// </summary> public static bool TryParse(string? version, out LanguageVersion result) { if (version == null) { result = LanguageVersion.Default; return true; } switch (CaseInsensitiveComparison.ToLower(version)) { case "default": result = LanguageVersion.Default; return true; case "latest": result = LanguageVersion.Latest; return true; case "latestmajor": result = LanguageVersion.LatestMajor; return true; case "preview": result = LanguageVersion.Preview; return true; case "1": case "1.0": case "iso-1": result = LanguageVersion.CSharp1; return true; case "2": case "2.0": case "iso-2": result = LanguageVersion.CSharp2; return true; case "3": case "3.0": result = LanguageVersion.CSharp3; return true; case "4": case "4.0": result = LanguageVersion.CSharp4; return true; case "5": case "5.0": result = LanguageVersion.CSharp5; return true; case "6": case "6.0": result = LanguageVersion.CSharp6; return true; case "7": case "7.0": result = LanguageVersion.CSharp7; return true; case "7.1": result = LanguageVersion.CSharp7_1; return true; case "7.2": result = LanguageVersion.CSharp7_2; return true; case "7.3": result = LanguageVersion.CSharp7_3; return true; case "8": case "8.0": result = LanguageVersion.CSharp8; return true; case "9": case "9.0": result = LanguageVersion.CSharp9; return true; case "10": case "10.0": result = LanguageVersion.CSharp10; return true; default: result = LanguageVersion.Default; return false; } } /// <summary> /// Map a language version (such as Default, Latest, or CSharpN) to a specific version (CSharpM). /// </summary> public static LanguageVersion MapSpecifiedToEffectiveVersion(this LanguageVersion version) { switch (version) { case LanguageVersion.Latest: case LanguageVersion.Default: case LanguageVersion.LatestMajor: return LanguageVersion.CSharp10; default: return version; } } internal static LanguageVersion CurrentVersion => LanguageVersion.CSharp10; /// <summary>Inference of tuple element names was added in C# 7.1</summary> internal static bool DisallowInferredTupleElementNames(this LanguageVersion self) { return self < MessageID.IDS_FeatureInferredTupleNames.RequiredVersion(); } internal static bool AllowNonTrailingNamedArguments(this LanguageVersion self) { return self >= MessageID.IDS_FeatureNonTrailingNamedArguments.RequiredVersion(); } internal static bool AllowAttributesOnBackingFields(this LanguageVersion self) { return self >= MessageID.IDS_FeatureAttributesOnBackingFields.RequiredVersion(); } internal static bool AllowImprovedOverloadCandidates(this LanguageVersion self) { return self >= MessageID.IDS_FeatureImprovedOverloadCandidates.RequiredVersion(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Specifies the language version. /// </summary> public enum LanguageVersion { /// <summary> /// C# language version 1 /// </summary> CSharp1 = 1, /// <summary> /// C# language version 2 /// </summary> CSharp2 = 2, /// <summary> /// C# language version 3 /// </summary> /// <remarks> /// Features: LINQ. /// </remarks> CSharp3 = 3, /// <summary> /// C# language version 4 /// </summary> /// <remarks> /// Features: dynamic. /// </remarks> CSharp4 = 4, /// <summary> /// C# language version 5 /// </summary> /// <remarks> /// Features: async, caller info attributes. /// </remarks> CSharp5 = 5, /// <summary> /// C# language version 6 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Using of a static class</description></item> /// <item><description>Exception filters</description></item> /// <item><description>Await in catch/finally blocks</description></item> /// <item><description>Auto-property initializers</description></item> /// <item><description>Expression-bodied methods and properties</description></item> /// <item><description>Null-propagating operator ?.</description></item> /// <item><description>String interpolation</description></item> /// <item><description>nameof operator</description></item> /// <item><description>Dictionary initializer</description></item> /// </list> /// </remarks> CSharp6 = 6, /// <summary> /// C# language version 7.0 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Out variables</description></item> /// <item><description>Pattern-matching</description></item> /// <item><description>Tuples</description></item> /// <item><description>Deconstruction</description></item> /// <item><description>Discards</description></item> /// <item><description>Local functions</description></item> /// <item><description>Digit separators</description></item> /// <item><description>Ref returns and locals</description></item> /// <item><description>Generalized async return types</description></item> /// <item><description>More expression-bodied members</description></item> /// <item><description>Throw expressions</description></item> /// </list> /// </remarks> CSharp7 = 7, /// <summary> /// C# language version 7.1 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Async Main</description></item> /// <item><description>Default literal</description></item> /// <item><description>Inferred tuple element names</description></item> /// <item><description>Pattern-matching with generics</description></item> /// </list> /// </remarks> CSharp7_1 = 701, /// <summary> /// C# language version 7.2 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Ref readonly</description></item> /// <item><description>Ref and readonly structs</description></item> /// <item><description>Ref extensions</description></item> /// <item><description>Conditional ref operator</description></item> /// <item><description>Private protected</description></item> /// <item><description>Digit separators after base specifier</description></item> /// <item><description>Non-trailing named arguments</description></item> /// </list> /// </remarks> CSharp7_2 = 702, /// <summary> /// C# language version 7.3 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Indexing fixed fields does not require pinning</description></item> /// <item><description>ref local variables may be reassigned</description></item> /// <item><description>stackalloc arrays support initializers</description></item> /// <item><description>More types support the fixed statement</description></item> /// <item><description>Enhanced generic constraints</description></item> /// <item><description>Tuples support == and !=</description></item> /// <item><description>Attach attributes to the backing fields for auto-implemented properties</description></item> /// <item><description>Method overload resolution improvements when arguments differ by 'in'</description></item> /// <item><description>Extend expression variables in initializers</description></item> /// <item><description>Improved overload candidates</description></item> /// <item><description>New compiler options (-publicsign and -pathmap)</description></item> /// </list> /// </remarks> CSharp7_3 = 703, /// <summary> /// C# language version 8.0 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Readonly members</description></item> /// <item><description>Default interface methods</description></item> /// <item><description>Pattern matching enhancements (switch expressions, property patterns, tuple patterns, and positional patterns)</description></item> /// <item><description>Using declarations</description></item> /// <item><description>Static local functions</description></item> /// <item><description>Disposable ref structs</description></item> /// <item><description>Nullable reference types</description></item> /// <item><description>Asynchronous streams</description></item> /// <item><description>Asynchronous disposable</description></item> /// <item><description>Indices and ranges</description></item> /// <item><description>Null-coalescing assignment</description></item> /// <item><description>Unmanaged constructed types</description></item> /// <item><description>Stackalloc in nested expressions</description></item> /// <item><description>Enhancement of interpolated verbatim strings</description></item> /// </list> /// </remarks> CSharp8 = 800, /// <summary> /// C# language version 9.0 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Records</description></item> /// <item><description>Init only setters</description></item> /// <item><description>Top-level statements</description></item> /// <item><description>Pattern matching enhancements</description></item> /// <item><description>Native sized integers</description></item> /// <item><description>Function pointers</description></item> /// <item><description>Suppress emitting localsinit flag</description></item> /// <item><description>Target-typed new expressions</description></item> /// <item><description>Static anonymous functions</description></item> /// <item><description>Target-typed conditional expressions</description></item> /// <item><description>Covariant return types</description></item> /// <item><description>Extension GetEnumerator support for foreach loops</description></item> /// <item><description>Lambda discard parameters</description></item> /// <item><description>Attributes on local functions</description></item> /// <item><description>Module initializers</description></item> /// <item><description>New features for partial methods</description></item> /// </list> /// </remarks> CSharp9 = 900, /// <summary> /// C# language version 10.0 /// </summary> /// <remarks> /// <para>Features:</para> /// <list type="bullet"> /// <item><description>Record structs</description></item> /// <item><description>Global using directives</description></item> /// <item><description>Lambda improvements</description></item> /// <item><description>Improved definite assignment</description></item> /// <item><description>Constant interpolated strings</description></item> /// <item><description>Mix declarations and variables in deconstruction</description></item> /// <item><description>Extended property patterns</description></item> /// <item><description>Sealed record ToString</description></item> /// <item><description>Source Generator v2 APIs</description></item> /// <item><description>Method-level AsyncMethodBuilder</description></item> /// </list> /// </remarks> CSharp10 = 1000, /// <summary> /// The latest major supported version. /// </summary> LatestMajor = int.MaxValue - 2, /// <summary> /// Preview of the next language version. /// </summary> Preview = int.MaxValue - 1, /// <summary> /// The latest supported version of the language. /// </summary> Latest = int.MaxValue, /// <summary> /// The default language version, which is the latest supported version. /// </summary> Default = 0, } internal static class LanguageVersionExtensionsInternal { internal static bool IsValid(this LanguageVersion value) { switch (value) { case LanguageVersion.CSharp1: case LanguageVersion.CSharp2: case LanguageVersion.CSharp3: case LanguageVersion.CSharp4: case LanguageVersion.CSharp5: case LanguageVersion.CSharp6: case LanguageVersion.CSharp7: case LanguageVersion.CSharp7_1: case LanguageVersion.CSharp7_2: case LanguageVersion.CSharp7_3: case LanguageVersion.CSharp8: case LanguageVersion.CSharp9: case LanguageVersion.CSharp10: case LanguageVersion.Preview: return true; } return false; } internal static ErrorCode GetErrorCode(this LanguageVersion version) { switch (version) { case LanguageVersion.CSharp1: return ErrorCode.ERR_FeatureNotAvailableInVersion1; case LanguageVersion.CSharp2: return ErrorCode.ERR_FeatureNotAvailableInVersion2; case LanguageVersion.CSharp3: return ErrorCode.ERR_FeatureNotAvailableInVersion3; case LanguageVersion.CSharp4: return ErrorCode.ERR_FeatureNotAvailableInVersion4; case LanguageVersion.CSharp5: return ErrorCode.ERR_FeatureNotAvailableInVersion5; case LanguageVersion.CSharp6: return ErrorCode.ERR_FeatureNotAvailableInVersion6; case LanguageVersion.CSharp7: return ErrorCode.ERR_FeatureNotAvailableInVersion7; case LanguageVersion.CSharp7_1: return ErrorCode.ERR_FeatureNotAvailableInVersion7_1; case LanguageVersion.CSharp7_2: return ErrorCode.ERR_FeatureNotAvailableInVersion7_2; case LanguageVersion.CSharp7_3: return ErrorCode.ERR_FeatureNotAvailableInVersion7_3; case LanguageVersion.CSharp8: return ErrorCode.ERR_FeatureNotAvailableInVersion8; case LanguageVersion.CSharp9: return ErrorCode.ERR_FeatureNotAvailableInVersion9; case LanguageVersion.CSharp10: return ErrorCode.ERR_FeatureNotAvailableInVersion10; default: throw ExceptionUtilities.UnexpectedValue(version); } } } internal class CSharpRequiredLanguageVersion : RequiredLanguageVersion { internal LanguageVersion Version { get; } internal CSharpRequiredLanguageVersion(LanguageVersion version) { Version = version; } public override string ToString() => Version.ToDisplayString(); } public static class LanguageVersionFacts { /// <summary> /// Usages of TestOptions.RegularNext and LanguageVersionFacts.CSharpNext /// will be replaced with TestOptions.RegularN and LanguageVersion.CSharpN when language version N is introduced. /// </summary> internal const LanguageVersion CSharpNext = LanguageVersion.Preview; /// <summary> /// Displays the version number in the format expected on the command-line (/langver flag). /// For instance, "6", "7.0", "7.1", "latest". /// </summary> public static string ToDisplayString(this LanguageVersion version) { switch (version) { case LanguageVersion.CSharp1: return "1"; case LanguageVersion.CSharp2: return "2"; case LanguageVersion.CSharp3: return "3"; case LanguageVersion.CSharp4: return "4"; case LanguageVersion.CSharp5: return "5"; case LanguageVersion.CSharp6: return "6"; case LanguageVersion.CSharp7: return "7.0"; case LanguageVersion.CSharp7_1: return "7.1"; case LanguageVersion.CSharp7_2: return "7.2"; case LanguageVersion.CSharp7_3: return "7.3"; case LanguageVersion.CSharp8: return "8.0"; case LanguageVersion.CSharp9: return "9.0"; case LanguageVersion.CSharp10: return "10.0"; case LanguageVersion.Default: return "default"; case LanguageVersion.Latest: return "latest"; case LanguageVersion.LatestMajor: return "latestmajor"; case LanguageVersion.Preview: return "preview"; default: throw ExceptionUtilities.UnexpectedValue(version); } } /// <summary> /// Try parse a <see cref="LanguageVersion"/> from a string input, returning default if input was null. /// </summary> public static bool TryParse(string? version, out LanguageVersion result) { if (version == null) { result = LanguageVersion.Default; return true; } switch (CaseInsensitiveComparison.ToLower(version)) { case "default": result = LanguageVersion.Default; return true; case "latest": result = LanguageVersion.Latest; return true; case "latestmajor": result = LanguageVersion.LatestMajor; return true; case "preview": result = LanguageVersion.Preview; return true; case "1": case "1.0": case "iso-1": result = LanguageVersion.CSharp1; return true; case "2": case "2.0": case "iso-2": result = LanguageVersion.CSharp2; return true; case "3": case "3.0": result = LanguageVersion.CSharp3; return true; case "4": case "4.0": result = LanguageVersion.CSharp4; return true; case "5": case "5.0": result = LanguageVersion.CSharp5; return true; case "6": case "6.0": result = LanguageVersion.CSharp6; return true; case "7": case "7.0": result = LanguageVersion.CSharp7; return true; case "7.1": result = LanguageVersion.CSharp7_1; return true; case "7.2": result = LanguageVersion.CSharp7_2; return true; case "7.3": result = LanguageVersion.CSharp7_3; return true; case "8": case "8.0": result = LanguageVersion.CSharp8; return true; case "9": case "9.0": result = LanguageVersion.CSharp9; return true; case "10": case "10.0": result = LanguageVersion.CSharp10; return true; default: result = LanguageVersion.Default; return false; } } /// <summary> /// Map a language version (such as Default, Latest, or CSharpN) to a specific version (CSharpM). /// </summary> public static LanguageVersion MapSpecifiedToEffectiveVersion(this LanguageVersion version) { switch (version) { case LanguageVersion.Latest: case LanguageVersion.Default: case LanguageVersion.LatestMajor: return LanguageVersion.CSharp10; default: return version; } } internal static LanguageVersion CurrentVersion => LanguageVersion.CSharp10; /// <summary>Inference of tuple element names was added in C# 7.1</summary> internal static bool DisallowInferredTupleElementNames(this LanguageVersion self) { return self < MessageID.IDS_FeatureInferredTupleNames.RequiredVersion(); } internal static bool AllowNonTrailingNamedArguments(this LanguageVersion self) { return self >= MessageID.IDS_FeatureNonTrailingNamedArguments.RequiredVersion(); } internal static bool AllowAttributesOnBackingFields(this LanguageVersion self) { return self >= MessageID.IDS_FeatureAttributesOnBackingFields.RequiredVersion(); } internal static bool AllowImprovedOverloadCandidates(this LanguageVersion self) { return self >= MessageID.IDS_FeatureImprovedOverloadCandidates.RequiredVersion(); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/UncheckedUnaryPlusMinusNot.txt
-=-=-=-=-=-=-=-=- + SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Parameter( x type: System.SByte ) } return type: System.SByte type: System.Func`2[System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- + SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Parameter( x type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`2[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- + E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`2[E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- + E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`2[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- + Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Parameter( x type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- + Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Parameter( x type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`2[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- + E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: E_Byte ) } return type: E_Byte type: System.Func`2[E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- + E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`2[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- + Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Parameter( x type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- + Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Parameter( x type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`2[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- + E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Convert( Parameter( x type: E_Short ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`2[E_Short,E_Short] ) -=-=-=-=-=-=-=-=- + E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`2[System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- + UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Parameter( x type: System.UInt16 ) } return type: System.UInt16 type: System.Func`2[System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- + UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Parameter( x type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`2[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- + E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) type: E_UShort ) } return type: E_UShort type: System.Func`2[E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- + E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`2[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- + Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Parameter( x type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- + Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Parameter( x type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`2[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- + E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`2[E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- + E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`2[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- + UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Parameter( x type: System.UInt32 ) } return type: System.UInt32 type: System.Func`2[System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- + UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Parameter( x type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`2[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- + E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`2[E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- + E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`2[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- + Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Parameter( x type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- + Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Parameter( x type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`2[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- + E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`2[E_Long,E_Long] ) -=-=-=-=-=-=-=-=- + E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- + ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) body { Parameter( x type: System.UInt64 ) } return type: System.UInt64 type: System.Func`2[System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- + ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) body { Parameter( x type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`2[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- + E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) body { Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`2[E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- + E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`2[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- + Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Convert( Negate( Convert( Parameter( x type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- + Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`2[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- + Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Parameter( x type: System.Single ) } return type: System.Single type: System.Func`2[System.Single,System.Single] ) -=-=-=-=-=-=-=-=- + Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Parameter( x type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`2[System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- + Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Parameter( x type: System.Double ) } return type: System.Double type: System.Func`2[System.Double,System.Double] ) -=-=-=-=-=-=-=-=- + Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Parameter( x type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`2[System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- + Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Parameter( x type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- + Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Parameter( x type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`2[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.String,System.String] ) -=-=-=-=-=-=-=-=- + Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { UnaryPlus( Parameter( x type: System.Object ) method: System.Object PlusObject(System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] ) -=-=-=-=-=-=-=-=- - SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( Negate( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`2[System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- - SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`2[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- - E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Convert( Negate( Convert( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`2[E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- - E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( Convert( Negate( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`2[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- - Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Negate( Convert( Parameter( x type: System.Byte ) type: System.Int16 ) type: System.Int16 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- - Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`2[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- - E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Negate( Convert( Parameter( x type: E_Byte ) type: System.Int16 ) type: System.Int16 ) type: E_Byte ) } return type: E_Byte type: System.Func`2[E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- - E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`2[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- - Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Negate( Parameter( x type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- - Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Negate( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`2[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- - E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Negate( Convert( Parameter( x type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`2[E_Short,E_Short] ) -=-=-=-=-=-=-=-=- - E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`2[System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- - UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( Negate( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) type: System.Int32 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`2[System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- - UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`2[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- - E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Negate( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) type: System.Int32 ) type: E_UShort ) } return type: E_UShort type: System.Func`2[E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- - E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`2[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- - Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Negate( Parameter( x type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- - Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Negate( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`2[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- - E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Negate( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`2[E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- - E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`2[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- - UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Negate( Convert( Parameter( x type: System.UInt32 ) type: System.Int64 ) type: System.Int64 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`2[System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- - UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`2[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- - E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Negate( Convert( Parameter( x type: E_UInteger ) type: System.Int64 ) type: System.Int64 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`2[E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- - E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`2[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- - Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Negate( Parameter( x type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- - Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Negate( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`2[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- - E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Negate( Convert( Parameter( x type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`2[E_Long,E_Long] ) -=-=-=-=-=-=-=-=- - E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- - ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) body { Convert( Negate( Convert( Parameter( x type: System.UInt64 ) method: System.Decimal op_Implicit(UInt64) in System.Decimal type: System.Decimal ) method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Decimal ) method: UInt64 op_Explicit(System.Decimal) in System.Decimal type: System.UInt64 ) } return type: System.UInt64 type: System.Func`2[System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- - ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(UInt64) in System.Decimal type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: UInt64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`2[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- - E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) body { Convert( Convert( Negate( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: System.Decimal op_Implicit(UInt64) in System.Decimal type: System.Decimal ) method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Decimal ) method: UInt64 op_Explicit(System.Decimal) in System.Decimal type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`2[E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- - E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) body { Convert( Convert( Negate( Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(UInt64) in System.Decimal type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: UInt64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`2[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- - Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Convert( Negate( Negate( Convert( Parameter( x type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- - Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Negate( Negate( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`2[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- - Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Negate( Parameter( x type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Single,System.Single] ) -=-=-=-=-=-=-=-=- - Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Negate( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`2[System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- - Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Negate( Parameter( x type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Double,System.Double] ) -=-=-=-=-=-=-=-=- - Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Negate( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`2[System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- - Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Negate( Parameter( x type: System.Decimal ) method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- - Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Negate( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`2[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- - String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Negate( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.String,System.String] ) -=-=-=-=-=-=-=-=- - Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Negate( Parameter( x type: System.Object ) method: System.Object NegateObject(System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] ) -=-=-=-=-=-=-=-=- Not SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( Not( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`2[System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- Not SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`2[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- Not E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Convert( Not( Convert( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`2[E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- Not E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( Convert( Not( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`2[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Not Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Not( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Not Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`2[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Not E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Convert( Not( Convert( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) } return type: E_Byte type: System.Func`2[E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- Not E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( Convert( Not( Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`2[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Not Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Not( Parameter( x type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Not Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Not( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`2[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Not E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Not( Convert( Parameter( x type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`2[E_Short,E_Short] ) -=-=-=-=-=-=-=-=- Not E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`2[System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- Not UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Not( Parameter( x type: System.UInt16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`2[System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- Not UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Not( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`2[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- Not E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Not( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) } return type: E_UShort type: System.Func`2[E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- Not E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`2[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Not Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Not( Parameter( x type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Not Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Not( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`2[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Not E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Not( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`2[E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- Not E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`2[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- Not UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Not( Parameter( x type: System.UInt32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`2[System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- Not UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Not( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`2[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- Not E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Not( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`2[E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- Not E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`2[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Not Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Not( Parameter( x type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Not Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Not( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`2[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Not E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Not( Convert( Parameter( x type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`2[E_Long,E_Long] ) -=-=-=-=-=-=-=-=- Not E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- Not ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) body { Not( Parameter( x type: System.UInt64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`2[System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- Not ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) body { Not( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`2[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- Not E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) body { Convert( Not( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`2[E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- Not E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`2[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Not Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Not( Parameter( x type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Not Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Not( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`2[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Not Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Not( Convert( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Not Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`2[System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Not Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Not( Convert( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Not Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`2[System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Not Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Not( Convert( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Not Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`2[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Not String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Not( Convert( Parameter( x type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.String,System.String] ) -=-=-=-=-=-=-=-=- Not Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Not( Parameter( x type: System.Object ) method: System.Object NotObject(System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] )
-=-=-=-=-=-=-=-=- + SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Parameter( x type: System.SByte ) } return type: System.SByte type: System.Func`2[System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- + SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Parameter( x type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`2[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- + E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`2[E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- + E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`2[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- + Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Parameter( x type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- + Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Parameter( x type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`2[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- + E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: E_Byte ) } return type: E_Byte type: System.Func`2[E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- + E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`2[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- + Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Parameter( x type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- + Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Parameter( x type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`2[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- + E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Convert( Parameter( x type: E_Short ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`2[E_Short,E_Short] ) -=-=-=-=-=-=-=-=- + E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`2[System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- + UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Parameter( x type: System.UInt16 ) } return type: System.UInt16 type: System.Func`2[System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- + UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Parameter( x type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`2[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- + E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) type: E_UShort ) } return type: E_UShort type: System.Func`2[E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- + E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`2[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- + Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Parameter( x type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- + Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Parameter( x type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`2[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- + E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`2[E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- + E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`2[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- + UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Parameter( x type: System.UInt32 ) } return type: System.UInt32 type: System.Func`2[System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- + UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Parameter( x type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`2[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- + E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`2[E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- + E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`2[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- + Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Parameter( x type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- + Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Parameter( x type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`2[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- + E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Convert( Parameter( x type: E_Long ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`2[E_Long,E_Long] ) -=-=-=-=-=-=-=-=- + E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- + ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) body { Parameter( x type: System.UInt64 ) } return type: System.UInt64 type: System.Func`2[System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- + ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) body { Parameter( x type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`2[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- + E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) body { Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`2[E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- + E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) body { Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`2[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- + Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Convert( Negate( Convert( Parameter( x type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- + Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`2[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- + Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Parameter( x type: System.Single ) } return type: System.Single type: System.Func`2[System.Single,System.Single] ) -=-=-=-=-=-=-=-=- + Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Parameter( x type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`2[System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- + Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Parameter( x type: System.Double ) } return type: System.Double type: System.Func`2[System.Double,System.Double] ) -=-=-=-=-=-=-=-=- + Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Parameter( x type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`2[System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- + Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Parameter( x type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- + Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Parameter( x type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`2[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- + String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.String,System.String] ) -=-=-=-=-=-=-=-=- + Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { UnaryPlus( Parameter( x type: System.Object ) method: System.Object PlusObject(System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] ) -=-=-=-=-=-=-=-=- - SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( Negate( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`2[System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- - SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`2[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- - E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Convert( Negate( Convert( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`2[E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- - E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( Convert( Negate( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`2[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- - Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Negate( Convert( Parameter( x type: System.Byte ) type: System.Int16 ) type: System.Int16 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- - Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`2[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- - E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Negate( Convert( Parameter( x type: E_Byte ) type: System.Int16 ) type: System.Int16 ) type: E_Byte ) } return type: E_Byte type: System.Func`2[E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- - E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`2[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- - Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Negate( Parameter( x type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- - Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Negate( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`2[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- - E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Negate( Convert( Parameter( x type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`2[E_Short,E_Short] ) -=-=-=-=-=-=-=-=- - E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`2[System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- - UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Convert( Negate( Convert( Parameter( x type: System.UInt16 ) type: System.Int32 ) type: System.Int32 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`2[System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- - UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`2[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- - E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Negate( Convert( Parameter( x type: E_UShort ) type: System.Int32 ) type: System.Int32 ) type: E_UShort ) } return type: E_UShort type: System.Func`2[E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- - E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`2[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- - Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Negate( Parameter( x type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- - Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Negate( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`2[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- - E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Negate( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`2[E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- - E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`2[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- - UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Convert( Negate( Convert( Parameter( x type: System.UInt32 ) type: System.Int64 ) type: System.Int64 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`2[System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- - UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`2[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- - E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Negate( Convert( Parameter( x type: E_UInteger ) type: System.Int64 ) type: System.Int64 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`2[E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- - E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`2[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- - Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Negate( Parameter( x type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- - Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Negate( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`2[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- - E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Negate( Convert( Parameter( x type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`2[E_Long,E_Long] ) -=-=-=-=-=-=-=-=- - E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- - ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) body { Convert( Negate( Convert( Parameter( x type: System.UInt64 ) method: System.Decimal op_Implicit(UInt64) in System.Decimal type: System.Decimal ) method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Decimal ) method: UInt64 op_Explicit(System.Decimal) in System.Decimal type: System.UInt64 ) } return type: System.UInt64 type: System.Func`2[System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- - ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) body { Convert( Negate( Convert( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(UInt64) in System.Decimal type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: UInt64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`2[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- - E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) body { Convert( Convert( Negate( Convert( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) method: System.Decimal op_Implicit(UInt64) in System.Decimal type: System.Decimal ) method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Decimal ) method: UInt64 op_Explicit(System.Decimal) in System.Decimal type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`2[E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- - E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) body { Convert( Convert( Negate( Convert( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(UInt64) in System.Decimal type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: UInt64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`2[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- - Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Convert( Convert( Negate( Negate( Convert( Parameter( x type: System.Boolean ) type: System.Int16 ) type: System.Int16 ) type: System.Int16 ) type: System.Int32 ) method: Boolean ToBoolean(Int32) in System.Convert type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- - Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Convert( Convert( Negate( Negate( Convert( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull method: Boolean ToBoolean(Int32) in System.Convert type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`2[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- - Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Negate( Parameter( x type: System.Single ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Single,System.Single] ) -=-=-=-=-=-=-=-=- - Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Negate( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`2[System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- - Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Negate( Parameter( x type: System.Double ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Double,System.Double] ) -=-=-=-=-=-=-=-=- - Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Negate( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`2[System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- - Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Negate( Parameter( x type: System.Decimal ) method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- - Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Negate( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: System.Decimal Negate(System.Decimal) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`2[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- - String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Negate( Convert( Parameter( x type: System.String ) method: Double ToDouble(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Double ) type: System.Double ) method: System.String ToString(Double) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.String,System.String] ) -=-=-=-=-=-=-=-=- - Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Negate( Parameter( x type: System.Object ) method: System.Object NegateObject(System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] ) -=-=-=-=-=-=-=-=- Not SByte => SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.SByte ) body { Convert( Not( Convert( Parameter( x type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) } return type: System.SByte type: System.Func`2[System.SByte,System.SByte] ) -=-=-=-=-=-=-=-=- Not SByte? => SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.SByte] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`2[System.Nullable`1[System.SByte],System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- Not E_SByte => E_SByte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_SByte ) body { Convert( Convert( Not( Convert( Convert( Parameter( x type: E_SByte ) type: System.SByte ) type: System.Int32 ) type: System.Int32 ) type: System.SByte ) type: E_SByte ) } return type: E_SByte type: System.Func`2[E_SByte,E_SByte] ) -=-=-=-=-=-=-=-=- Not E_SByte? => E_SByte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_SByte] ) body { Convert( Convert( Not( Convert( Convert( Parameter( x type: System.Nullable`1[E_SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.SByte] ) Lifted LiftedToNull type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`2[System.Nullable`1[E_SByte],System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Not Byte => Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Byte ) body { Convert( Not( Convert( Parameter( x type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) } return type: System.Byte type: System.Func`2[System.Byte,System.Byte] ) -=-=-=-=-=-=-=-=- Not Byte? => Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Byte] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`2[System.Nullable`1[System.Byte],System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Not E_Byte => E_Byte -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Byte ) body { Convert( Convert( Not( Convert( Convert( Parameter( x type: E_Byte ) type: System.Byte ) type: System.Int32 ) type: System.Int32 ) type: System.Byte ) type: E_Byte ) } return type: E_Byte type: System.Func`2[E_Byte,E_Byte] ) -=-=-=-=-=-=-=-=- Not E_Byte? => E_Byte? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Byte] ) body { Convert( Convert( Not( Convert( Convert( Parameter( x type: System.Nullable`1[E_Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Byte] ) Lifted LiftedToNull type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`2[System.Nullable`1[E_Byte],System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Not Short => Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int16 ) body { Not( Parameter( x type: System.Int16 ) type: System.Int16 ) } return type: System.Int16 type: System.Func`2[System.Int16,System.Int16] ) -=-=-=-=-=-=-=-=- Not Short? => Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int16] ) body { Not( Parameter( x type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`2[System.Nullable`1[System.Int16],System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Not E_Short => E_Short -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Short ) body { Convert( Not( Convert( Parameter( x type: E_Short ) type: System.Int16 ) type: System.Int16 ) type: E_Short ) } return type: E_Short type: System.Func`2[E_Short,E_Short] ) -=-=-=-=-=-=-=-=- Not E_Short? => E_Short? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Short] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_Short] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[System.Int16] ) Lifted LiftedToNull type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`2[System.Nullable`1[E_Short],System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- Not UShort => UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt16 ) body { Not( Parameter( x type: System.UInt16 ) type: System.UInt16 ) } return type: System.UInt16 type: System.Func`2[System.UInt16,System.UInt16] ) -=-=-=-=-=-=-=-=- Not UShort? => UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt16] ) body { Not( Parameter( x type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`2[System.Nullable`1[System.UInt16],System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- Not E_UShort => E_UShort -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UShort ) body { Convert( Not( Convert( Parameter( x type: E_UShort ) type: System.UInt16 ) type: System.UInt16 ) type: E_UShort ) } return type: E_UShort type: System.Func`2[E_UShort,E_UShort] ) -=-=-=-=-=-=-=-=- Not E_UShort? => E_UShort? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UShort] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_UShort] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt16] ) Lifted LiftedToNull type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`2[System.Nullable`1[E_UShort],System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Not Integer => Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int32 ) body { Not( Parameter( x type: System.Int32 ) type: System.Int32 ) } return type: System.Int32 type: System.Func`2[System.Int32,System.Int32] ) -=-=-=-=-=-=-=-=- Not Integer? => Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int32] ) body { Not( Parameter( x type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`2[System.Nullable`1[System.Int32],System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Not E_Integer => E_Integer -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Integer ) body { Convert( Not( Convert( Parameter( x type: E_Integer ) type: System.Int32 ) type: System.Int32 ) type: E_Integer ) } return type: E_Integer type: System.Func`2[E_Integer,E_Integer] ) -=-=-=-=-=-=-=-=- Not E_Integer? => E_Integer? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Integer] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_Integer] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[System.Int32] ) Lifted LiftedToNull type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`2[System.Nullable`1[E_Integer],System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- Not UInteger => UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt32 ) body { Not( Parameter( x type: System.UInt32 ) type: System.UInt32 ) } return type: System.UInt32 type: System.Func`2[System.UInt32,System.UInt32] ) -=-=-=-=-=-=-=-=- Not UInteger? => UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt32] ) body { Not( Parameter( x type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`2[System.Nullable`1[System.UInt32],System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- Not E_UInteger => E_UInteger -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_UInteger ) body { Convert( Not( Convert( Parameter( x type: E_UInteger ) type: System.UInt32 ) type: System.UInt32 ) type: E_UInteger ) } return type: E_UInteger type: System.Func`2[E_UInteger,E_UInteger] ) -=-=-=-=-=-=-=-=- Not E_UInteger? => E_UInteger? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_UInteger] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_UInteger] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt32] ) Lifted LiftedToNull type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`2[System.Nullable`1[E_UInteger],System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Not Long => Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Int64 ) body { Not( Parameter( x type: System.Int64 ) type: System.Int64 ) } return type: System.Int64 type: System.Func`2[System.Int64,System.Int64] ) -=-=-=-=-=-=-=-=- Not Long? => Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Int64] ) body { Not( Parameter( x type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`2[System.Nullable`1[System.Int64],System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Not E_Long => E_Long -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_Long ) body { Convert( Not( Convert( Parameter( x type: E_Long ) type: System.Int64 ) type: System.Int64 ) type: E_Long ) } return type: E_Long type: System.Func`2[E_Long,E_Long] ) -=-=-=-=-=-=-=-=- Not E_Long? => E_Long? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_Long] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_Long] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`2[System.Nullable`1[E_Long],System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- Not ULong => ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.UInt64 ) body { Not( Parameter( x type: System.UInt64 ) type: System.UInt64 ) } return type: System.UInt64 type: System.Func`2[System.UInt64,System.UInt64] ) -=-=-=-=-=-=-=-=- Not ULong? => ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.UInt64] ) body { Not( Parameter( x type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) } return type: System.Nullable`1[System.UInt64] type: System.Func`2[System.Nullable`1[System.UInt64],System.Nullable`1[System.UInt64]] ) -=-=-=-=-=-=-=-=- Not E_ULong => E_ULong -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: E_ULong ) body { Convert( Not( Convert( Parameter( x type: E_ULong ) type: System.UInt64 ) type: System.UInt64 ) type: E_ULong ) } return type: E_ULong type: System.Func`2[E_ULong,E_ULong] ) -=-=-=-=-=-=-=-=- Not E_ULong? => E_ULong? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[E_ULong] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[E_ULong] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[System.UInt64] ) Lifted LiftedToNull type: System.Nullable`1[E_ULong] ) } return type: System.Nullable`1[E_ULong] type: System.Func`2[System.Nullable`1[E_ULong],System.Nullable`1[E_ULong]] ) -=-=-=-=-=-=-=-=- Not Boolean => Boolean -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Boolean ) body { Not( Parameter( x type: System.Boolean ) type: System.Boolean ) } return type: System.Boolean type: System.Func`2[System.Boolean,System.Boolean] ) -=-=-=-=-=-=-=-=- Not Boolean? => Boolean? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Boolean] ) body { Not( Parameter( x type: System.Nullable`1[System.Boolean] ) Lifted LiftedToNull type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`2[System.Nullable`1[System.Boolean],System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Not Single => Single -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Single ) body { Convert( Not( Convert( Parameter( x type: System.Single ) method: Int64 ToInt64(Single) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Single ) } return type: System.Single type: System.Func`2[System.Single,System.Single] ) -=-=-=-=-=-=-=-=- Not Single? => Single? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Single] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[System.Single] ) Lifted LiftedToNull method: Int64 ToInt64(Single) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`2[System.Nullable`1[System.Single],System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Not Double => Double -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Double ) body { Convert( Not( Convert( Parameter( x type: System.Double ) method: Int64 ToInt64(Double) in System.Convert type: System.Int64 ) type: System.Int64 ) type: System.Double ) } return type: System.Double type: System.Func`2[System.Double,System.Double] ) -=-=-=-=-=-=-=-=- Not Double? => Double? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Double] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[System.Double] ) Lifted LiftedToNull method: Int64 ToInt64(Double) in System.Convert type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`2[System.Nullable`1[System.Double],System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Not Decimal => Decimal -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Decimal ) body { Convert( Not( Convert( Parameter( x type: System.Decimal ) method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Int64 ) type: System.Int64 ) method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Decimal ) } return type: System.Decimal type: System.Func`2[System.Decimal,System.Decimal] ) -=-=-=-=-=-=-=-=- Not Decimal? => Decimal? -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Nullable`1[System.Decimal] ) body { Convert( Not( Convert( Parameter( x type: System.Nullable`1[System.Decimal] ) Lifted LiftedToNull method: Int64 op_Explicit(System.Decimal) in System.Decimal type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull type: System.Nullable`1[System.Int64] ) Lifted LiftedToNull method: System.Decimal op_Implicit(Int64) in System.Decimal type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`2[System.Nullable`1[System.Decimal],System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Not String => String -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.String ) body { Convert( Not( Convert( Parameter( x type: System.String ) method: Int64 ToLong(System.String) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.Int64 ) type: System.Int64 ) method: System.String ToString(Int64) in Microsoft.VisualBasic.CompilerServices.Conversions type: System.String ) } return type: System.String type: System.Func`2[System.String,System.String] ) -=-=-=-=-=-=-=-=- Not Object => Object -=-=-=-=-=-=-=-=- Lambda( Parameter( x type: System.Object ) body { Not( Parameter( x type: System.Object ) method: System.Object NotObject(System.Object) in Microsoft.VisualBasic.CompilerServices.Operators type: System.Object ) } return type: System.Object type: System.Func`2[System.Object,System.Object] )
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/CSharp/EditorConfigSettings/DataProvider/CodeStyle/CSharpCodeStyleSettingsProviderFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings.DataProvider.CodeStyle { internal class CSharpCodeStyleSettingsProviderFactory : ILanguageSettingsProviderFactory<CodeStyleSetting> { private readonly Workspace _workspace; public CSharpCodeStyleSettingsProviderFactory(Workspace workspace) => _workspace = workspace; public ISettingsProvider<CodeStyleSetting> GetForFile(string filePath) => new CSharpCodeStyleSettingsProvider(filePath, new OptionUpdater(_workspace, filePath), _workspace); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Updater; namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings.DataProvider.CodeStyle { internal class CSharpCodeStyleSettingsProviderFactory : ILanguageSettingsProviderFactory<CodeStyleSetting> { private readonly Workspace _workspace; public CSharpCodeStyleSettingsProviderFactory(Workspace workspace) => _workspace = workspace; public ISettingsProvider<CodeStyleSetting> GetForFile(string filePath) => new CSharpCodeStyleSettingsProvider(filePath, new OptionUpdater(_workspace, filePath), _workspace); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/GroupByKeywordRecommender.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.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries ''' <summary> ''' Recommends the "By" keyword for the "Group By" query clause. ''' </summary> Friend Class GroupByKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("By", VBFeaturesResources.Specifies_the_element_keys_used_for_grouping_in_Group_By_or_sort_order_in_Order_By)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If If context.TargetToken.IsChildToken(Of GroupByClauseSyntax)(Function(groupBy) groupBy.GroupKeyword) OrElse context.SyntaxTree.IsFollowingCompleteExpression(Of GroupByClauseSyntax)( context.Position, context.TargetToken, Function(groupBy) groupBy.Items.LastRangeExpression(), cancellationToken) Then Return s_keywords End If Return ImmutableArray(Of RecommendedKeyword).Empty 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.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries ''' <summary> ''' Recommends the "By" keyword for the "Group By" query clause. ''' </summary> Friend Class GroupByKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("By", VBFeaturesResources.Specifies_the_element_keys_used_for_grouping_in_Group_By_or_sort_order_in_Order_By)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If If context.TargetToken.IsChildToken(Of GroupByClauseSyntax)(Function(groupBy) groupBy.GroupKeyword) OrElse context.SyntaxTree.IsFollowingCompleteExpression(Of GroupByClauseSyntax)( context.Position, context.TargetToken, Function(groupBy) groupBy.Items.LastRangeExpression(), cancellationToken) Then Return s_keywords End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/CSharp/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.SigningTestHelpers; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class InternalsVisibleToAndStrongNameTests : CSharpTestBase { public static IEnumerable<object[]> AllProviderParseOptions { get { if (ExecutionConditionUtil.IsWindows) { return new[] { new object[] { TestOptions.Regular }, new object[] { TestOptions.RegularWithLegacyStrongName } }; } return SpecializedCollections.SingletonEnumerable(new object[] { TestOptions.Regular }); } } #region Helpers public InternalsVisibleToAndStrongNameTests() { SigningTestHelpers.InstallKey(); } private static readonly string s_keyPairFile = SigningTestHelpers.KeyPairFile; private static readonly string s_publicKeyFile = SigningTestHelpers.PublicKeyFile; private static readonly ImmutableArray<byte> s_publicKey = SigningTestHelpers.PublicKey; private static StrongNameProvider GetProviderWithPath(string keyFilePath) => new DesktopStrongNameProvider(ImmutableArray.Create(keyFilePath), strongNameFileSystem: new VirtualizedStrongNameFileSystem()); #endregion #region Naming Tests [WorkItem(529419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529419")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblyKeyFileAttributeNotExistFile(CSharpParseOptions parseOptions) { string source = @" using System; using System.Reflection; [assembly: AssemblyKeyFile(""MyKey.snk"")] [assembly: AssemblyKeyName(""Key Name"")] public class Test { public static void Main() { Console.Write(""Hello World!""); } } "; // Dev11 RC gives error now (CS1548) + two warnings // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keyfile", "AssemblyKeyFile"), // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keycontainer", "AssemblyKeyName") var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()), parseOptions: parseOptions); c.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("MyKey.snk", CodeAnalysisResources.FileNotFound)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); CompileAndVerify(other, symbolValidator: (ModuleSymbol m) => { bool haveAttribute = false; foreach (var attrData in m.ContainingAssembly.GetAttributes()) { if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyFileAttribute)) { haveAttribute = true; break; } } Assert.True(haveAttribute); }); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = string.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", parseOptions); // verify failure with default assembly key file resolver var comp = CreateCompilation(syntaxTree, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, "Assembly signing not supported.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(keyFileDir))); comp.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestHasWindowsPaths)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver_RelativeToCurrentParent(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", parseOptions); // verify failure with default assembly key file resolver var comp = CreateCompilation(syntaxTree, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file '..\KeyPairFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(@"..\" + keyFileName, "Assembly signing not supported.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir\TempSubDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\")))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestHasWindowsPaths)] public void SigningNotAvailable001() { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", TestOptions.RegularWithLegacyStrongName); var provider = new TestDesktopStrongNameProvider( ImmutableArray.Create(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\")), new VirtualizedStrongNameFileSystem()) { GetStrongNameInterfaceFunc = () => throw new DllNotFoundException("aaa.dll not found.") }; var options = TestOptions.ReleaseDll.WithStrongNameProvider(provider); // verify failure var comp = CreateCompilation( assemblyName: GetUniqueName(), source: new[] { syntaxTree }, options: options); comp.VerifyEmitDiagnostics( // error CS7027: Error signing output with public key from file '..\KeyPair_6187d0d6-f691-47fd-985b-03570bc0668d.snk' -- aaa.dll not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("..\\" + keyFileName, "aaa.dll not found.").WithLocation(1, 1) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyContainerAttribute(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); CompileAndVerify(other, symbolValidator: (ModuleSymbol m) => { bool haveAttribute = false; foreach (var attrData in m.ContainingAssembly.GetAttributes()) { if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyNameAttribute)) { haveAttribute = true; break; } } Assert.True(haveAttribute); }); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptions_ReferenceResolver(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = "public class C {}"; var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default resolver var comp = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(keyFileName), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file 'KeyPairFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, CodeAnalysisResources.FileNotFound)); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(GetProviderWithPath(keyFileDir))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptionsJustPublicKey(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(TestResources.General.snPublicKey.AsImmutableOrNull(), other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptionsJustPublicKey_ReferenceResolver(CSharpParseOptions parseOptions) { string publicKeyFileDir = Path.GetDirectoryName(s_publicKeyFile); string publicKeyFileName = Path.GetFileName(s_publicKeyFile); string s = "public class C {}"; var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default resolver var comp = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file 'PublicKeyFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(publicKeyFileName, CodeAnalysisResources.FileNotFound), // warning CS7033: Delay signing was specified and requires a public key, but no public key was specified Diagnostic(ErrorCode.WRN_DelaySignButNoKey) ); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with publicKeyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true).WithStrongNameProvider(GetProviderWithPath(publicKeyFileDir))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFileNotFoundOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile("goo"), parseOptions: parseOptions); other.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("goo", CodeAnalysisResources.FileNotFound)); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFileBogusOptions(CSharpParseOptions parseOptions) { var tempFile = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4 }); string s = "public class C {}"; CSharpCompilation other = CreateCompilation(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(tempFile.Path), parseOptions: parseOptions); //TODO check for specific error Assert.NotEmpty(other.GetDiagnostics()); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [WorkItem(5662, "https://github.com/dotnet/roslyn/issues/5662")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyContainerBogusOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyContainer("goo"), parseOptions: parseOptions); // error CS7028: Error signing output with public key from container 'goo' -- Keyset does not exist (Exception from HRESULT: 0x80090016) var err = other.GetDiagnostics().Single(); Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal("goo", err.Arguments[0]); Assert.True(((string)err.Arguments[1]).EndsWith("0x80090016)", StringComparison.Ordinal), (string)err.Arguments[1]); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileAttributeOptionConflict(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyFile", "System.Reflection.AssemblyKeyFileAttribute")); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerAttributeOptionConflict(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyContainer("RoslynTestContainer"), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyContainer", "System.Reflection.AssemblyKeyNameAttribute")); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileAttributeEmpty(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile("""")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); other.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerEmpty(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName("""")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); other.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_DelaySigned(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C {}"; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey), parseOptions: parseOptions); c.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)); var metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()); var identity = metadata.Module.ReadAssemblyIdentityOrThrow(); Assert.True(identity.HasPublicKey); AssertEx.Equal(identity.PublicKey, s_publicKey); Assert.Equal(CorFlags.ILOnly, metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_PublicSign(CSharpParseOptions parseOptions) { // attributes are ignored string source = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] [assembly: System.Reflection.AssemblyKeyFile(""some file"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyNameAttribute").WithLocation(1, 1), // warning CS7103: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyFileAttribute").WithLocation(1, 1) ); Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)); var metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()); var identity = metadata.Module.ReadAssemblyIdentityOrThrow(); Assert.True(identity.HasPublicKey); AssertEx.Equal(identity.PublicKey, s_publicKey); Assert.Equal(CorFlags.ILOnly | CorFlags.StrongNameSigned, metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags); c = CreateCompilation(source, options: TestOptions.SigningReleaseModule.WithCryptoPublicKey(s_publicKey).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); c = CreateCompilation(source, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_publicKeyFile).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS7091: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyFileAttribute", "CryptoKeyFile").WithLocation(1, 1), // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); string source1 = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] [assembly: System.Reflection.AssemblyKeyFile(@""" + snk.Path + @""")] public class C {} "; c = CreateCompilation(source1, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(snk.Path).WithPublicSign(true)); c.VerifyDiagnostics( // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileFromAttributes_PublicSign(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyKeyFile(""test.snk"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyFileAttribute").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); Assert.True(c.Options.PublicSign); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerFromAttributes_PublicSign(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyNameAttribute").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); Assert.True(c.Options.PublicSign); } private void VerifySignedBitSetAfterEmit(Compilation comp, bool expectedToBeSigned = true) { using (var outStream = comp.EmitToStream()) { outStream.Position = 0; using (var reader = new PEReader(outStream)) { var flags = reader.PEHeaders.CorHeader.Flags; Assert.Equal(expectedToBeSigned, flags.HasFlag(CorFlags.StrongNameSigned)); } } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SnkFile_PublicSign(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C{}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(snk.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFile_PublicSign(CSharpParseOptions parseOptions) { var pubKeyFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(pubKeyFile.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSign_DelaySignAttribute(CSharpParseOptions parseOptions) { var pubKeyFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey); var comp = CreateCompilation(@" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(pubKeyFile.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // warning CS1616: Option 'PublicSign' overrides attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file or added module Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("PublicSign", "System.Reflection.AssemblyDelaySignAttribute").WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerNoSNProvider_PublicSign(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyContainer("roslynTestContainer") .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "CryptoKeyContainer").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerDesktopProvider_PublicSign(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.SigningReleaseDll .WithCryptoKeyContainer("roslynTestContainer") .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "CryptoKeyContainer").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyContainer); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignAndDelaySign(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithPublicSign(true) .WithDelaySign(true) .WithCryptoKeyFile(snk.Path), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'DelaySign' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "DelaySign").WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.True(comp.Options.DelaySign); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignAndDelaySignFalse(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithPublicSign(true) .WithDelaySign(false) .WithCryptoKeyFile(snk.Path), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.False(comp.Options.DelaySign); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignNoKey(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.True(comp.Assembly.PublicKey.IsDefaultOrEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_InvalidCompilationOptions(CSharpParseOptions parseOptions) { string source = @"public class C {}"; var c = CreateCompilation(source, options: TestOptions.SigningReleaseDll. WithCryptoPublicKey(ImmutableArray.Create<byte>(1, 2, 3)). WithCryptoKeyContainer("roslynTestContainer"). WithCryptoKeyFile("file.snk"), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS7102: Compilation options 'CryptoPublicKey' and 'CryptoKeyFile' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("CryptoPublicKey", "CryptoKeyFile").WithLocation(1, 1), // error CS7102: Compilation options 'CryptoPublicKey' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("CryptoPublicKey", "CryptoKeyContainer").WithLocation(1, 1), // error CS7088: Invalid 'CryptoPublicKey' value: '01-02-03'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("CryptoPublicKey", "01-02-03").WithLocation(1, 1)); } #endregion #region IVT Access Checking [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTBasicCompilation(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, assemblyName: "Paul", parseOptions: parseOptions); var c = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { new CSharpCompilationReference(other) }, assemblyName: "WantsIVTAccessButCantHave", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //compilation should not succeed, and internals should not be imported. c.VerifyDiagnostics( // (7,15): error CS0122: 'C.Goo()' is inaccessible due to its protection level // o.Goo(); Diagnostic(ErrorCode.ERR_BadAccess, "Goo").WithArguments("C.Goo()").WithLocation(7, 15) ); var c2 = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { new CSharpCompilationReference(other) }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll); Assert.Empty(c2.GetDiagnostics()); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTBasicMetadata(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public class C { internal void Goo() {} }"; var otherStream = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions).EmitToStream(); var c = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { AssemblyMetadata.CreateFromStream(otherStream, leaveOpen: true).GetReference() }, assemblyName: "WantsIVTAccessButCantHave", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //compilation should not succeed, and internals should not be imported. c.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Goo").WithArguments("C", "Goo")); otherStream.Position = 0; var c2 = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { MetadataReference.CreateFromStream(otherStream) }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.Empty(c2.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTSigned(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll.WithCryptoKeyContainer("roslynTestContainer"), assemblyName: "John", parseOptions: parseOptions); Assert.Empty(requestor.GetDiagnostics()); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNotBothSigned_CStoCS(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); // We allow John to access Paul's internal Goo even though strong-named John should not be referencing weak-named Paul. // Paul has, after all, specifically granted access to John. // During emit time we should produce an error that says that a strong-named assembly cannot reference // a weak-named assembly. But the C# compiler doesn't currently do that. See https://github.com/dotnet/roslyn/issues/26722 requestor.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void CS0281Method(CSharpParseOptions parseOptions) { var friendClass = CreateCompilation(@" using System.Runtime.CompilerServices; [ assembly: InternalsVisibleTo(""cs0281, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"") ] public class PublicClass { internal static void InternalMethod() { } protected static void ProtectedMethod() { } private static void PrivateMethod() { } internal protected static void InternalProtectedMethod() { } private protected static void PrivateProtectedMethod() { } }", assemblyName: "Paul", parseOptions: parseOptions); string cs0281 = @" public class Test { static void Main () { PublicClass.InternalMethod(); PublicClass.ProtectedMethod(); PublicClass.PrivateMethod(); PublicClass.InternalProtectedMethod(); PublicClass.PrivateProtectedMethod(); } }"; var other = CreateCompilation(cs0281, references: new[] { friendClass.EmitToImageReference() }, assemblyName: "cs0281", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics( // (7,15): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.InternalMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "InternalMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(7, 15), // (8,21): error CS0122: 'PublicClass.ProtectedMethod()' is inaccessible due to its protection level // PublicClass.ProtectedMethod(); Diagnostic(ErrorCode.ERR_BadAccess, "ProtectedMethod").WithArguments("PublicClass.ProtectedMethod()").WithLocation(8, 21), // (9,21): error CS0117: 'PublicClass' does not contain a definition for 'PrivateMethod' // PublicClass.PrivateMethod(); Diagnostic(ErrorCode.ERR_NoSuchMember, "PrivateMethod").WithArguments("PublicClass", "PrivateMethod").WithLocation(9, 21), // (10,21): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.InternalProtectedMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "InternalProtectedMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(10, 21), // (11,21): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.PrivateProtectedMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "PrivateProtectedMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(11, 21) ); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void CS0281Class(CSharpParseOptions parseOptions) { var friendClass = CreateCompilation(@" using System.Runtime.CompilerServices; [ assembly: InternalsVisibleTo(""cs0281, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"") ] internal class FriendClass { public static void MyMethod() { } }", assemblyName: "Paul", parseOptions: parseOptions); string cs0281 = @" public class Test { static void Main () { FriendClass.MyMethod (); } }"; var other = CreateCompilation(cs0281, references: new[] { friendClass.EmitToImageReference() }, assemblyName: "cs0281", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); // (7, 3): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // FriendClass.MyMethod (); other.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "FriendClass").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(7, 3) ); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNotBothSigned_VBtoCS(CSharpParseOptions parseOptions) { string s = @"<assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")> Public Class C Friend Sub Goo() End Sub End Class"; var other = VisualBasic.VisualBasicCompilation.Create( syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(s) }, references: new[] { MscorlibRef_v4_0_30316_17626 }, assemblyName: "Paul", options: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithStrongNameProvider(DefaultDesktopStrongNameProvider)); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { MetadataReference.CreateFromImage(other.EmitToArray()) }, assemblyName: "John", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); // We allow John to access Paul's internal Goo even though strong-named John should not be referencing weak-named Paul. // Paul has, after all, specifically granted access to John. // During emit time we should produce an error that says that a strong-named assembly cannot reference // a weak-named assembly. But the C# compiler doesn't currently do that. See https://github.com/dotnet/roslyn/issues/26722 requestor.VerifyDiagnostics(); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredSuccess(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); Assert.Empty(requestor.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailSignMismatch(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //not signed. cryptoKeyFile: KeyPairFile, other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics(); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailSignMismatch_AssemblyKeyName(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //not signed. cryptoKeyFile: KeyPairFile, other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_FriendRefSigningMismatch, arguments: new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" })); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatch(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( // (2,12): error CS0122: 'CAttribute' is inaccessible due to its protection level // [assembly: C()] Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("CAttribute").WithLocation(2, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatch_AssemblyKeyName(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( // error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2', // but the public key of the output assembly ('John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis) .WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2") .WithLocation(1, 1), // (2,12): error CS0122: 'AssemblyKeyNameAttribute' is inaccessible due to its protection level // [assembly: AssemblyKeyName()] Diagnostic(ErrorCode.ERR_BadAccess, "AssemblyKeyName").WithArguments("AssemblyKeyNameAttribute").WithLocation(2, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTSuccessThroughIAssembly(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, options: TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.True(other.Assembly.GivesAccessTo(requestor.Assembly)); Assert.Empty(requestor.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatchIAssembly(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.False(other.Assembly.GivesAccessTo(requestor.Assembly)); requestor.VerifyDiagnostics( // (3,12): error CS0122: 'CAttribute' is inaccessible due to its protection level // [assembly: C()] Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("CAttribute").WithLocation(3, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatchIAssembly_AssemblyKeyName(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.False(other.Assembly.GivesAccessTo(requestor.Assembly)); requestor.VerifyDiagnostics( // error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2', // but the public key of the output assembly ('John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis) .WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2") .WithLocation(1, 1), // (3,12): error CS0122: 'AssemblyKeyNameAttribute' is inaccessible due to its protection level // [assembly: AssemblyKeyName()] Diagnostic(ErrorCode.ERR_BadAccess, "AssemblyKeyName").WithArguments("AssemblyKeyNameAttribute").WithLocation(3, 12) ); } [WorkItem(820450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820450")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTGivesAccessToUsingDifferentKeys(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] namespace ClassLibrary1 { internal class Class1 { } } "; var giver = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile2), parseOptions: parseOptions); giver.VerifyDiagnostics(); var requestor = CreateCompilation( @" namespace ClassLibrary2 { internal class A { public void Goo(ClassLibrary1.Class1 a) { } } }", new MetadataReference[] { new CSharpCompilationReference(giver) }, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "John", parseOptions: parseOptions); Assert.True(giver.Assembly.GivesAccessTo(requestor.Assembly)); Assert.Empty(requestor.GetDiagnostics()); } #endregion #region IVT instantiations [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTHasCulture(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")] public class C { static void Goo() {} } ", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")").WithArguments("WantsIVTAccess, Culture=neutral")); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNoKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""WantsIVTAccess"")] public class C { static void Main() {} } ", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblySNReq, @"InternalsVisibleTo(""WantsIVTAccess"")").WithArguments("WantsIVTAccess")); } #endregion #region Signing [ConditionalTheory(typeof(DesktopOnly), Reason = "https://github.com/dotnet/coreclr/issues/21723")] [MemberData(nameof(AllProviderParseOptions))] public void MaxSizeKey(CSharpParseOptions parseOptions) { var pubKey = TestResources.General.snMaxSizePublicKeyString; string pubKeyToken = "1540923db30520b2"; var pubKeyTokenBytes = new byte[] { 0x15, 0x40, 0x92, 0x3d, 0xb3, 0x05, 0x20, 0xb2 }; var comp = CreateCompilation($@" using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""MaxSizeComp2, PublicKey={pubKey}, PublicKeyToken={pubKeyToken}"")] internal class C {{ public static void M() {{ Console.WriteLine(""Called M""); }} }}", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); comp.VerifyEmitDiagnostics(); Assert.True(comp.IsRealSigned); VerifySignedBitSetAfterEmit(comp); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp.Assembly.Identity.PublicKeyToken); var src = @" class D { public static void Main() { C.M(); } }"; var comp2 = CreateCompilation(src, references: new[] { comp.ToMetadataReference() }, assemblyName: "MaxSizeComp2", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); CompileAndVerify(comp2, expectedOutput: "Called M"); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp2.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp2.Assembly.Identity.PublicKeyToken); var comp3 = CreateCompilation(src, references: new[] { comp.EmitToImageReference() }, assemblyName: "MaxSizeComp2", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); CompileAndVerify(comp3, expectedOutput: "Called M"); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp3.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp3.Assembly.Identity.PublicKeyToken); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignIt(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } private static bool IsFileFullSigned(TempFile file) { using (var metadata = new FileStream(file.Path, FileMode.Open)) { return ILValidation.IsStreamFullSigned(metadata); } } private void ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(MemoryStream moduleContents, AttributeDescription expectedModuleAttr, CSharpParseOptions parseOptions) { //a module doesn't get signed for real. It should have either a keyfile or keycontainer attribute //parked on a typeRef named 'AssemblyAttributesGoHere.' When the module is added to an assembly, the //resulting assembly is signed with the key referred to by the aforementioned attribute. EmitResult success; var tempFile = Temp.CreateFile(); moduleContents.Position = 0; using (var metadata = ModuleMetadata.CreateFromStream(moduleContents)) { var flags = metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags; //confirm file does not claim to be signed Assert.Equal(0, (int)(flags & CorFlags.StrongNameSigned)); var corlibName = RuntimeUtilities.IsCoreClrRuntime ? "netstandard" : "mscorlib"; EntityHandle token = metadata.Module.GetTypeRef(metadata.Module.GetAssemblyRef(corlibName), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var attrInfos = metadata.Module.FindTargetAttributes(token, expectedModuleAttr); Assert.Equal(1, attrInfos.Count()); var source = @" public class Z { }"; //now that the module checks out, ensure that adding it to a compilation outputting a dll //results in a signed assembly. var assemblyComp = CreateCompilation(source, new[] { metadata.GetReference() }, TestOptions.SigningReleaseDll, parseOptions: parseOptions); using (var finalStrm = tempFile.Open()) { success = assemblyComp.Emit(finalStrm); } } success.Diagnostics.Verify(); Assert.True(success.Success); Assert.True(IsFileFullSigned(tempFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileAttr(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); var outStrm = other.EmitToStream(); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerAttr(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); var outStrm = other.EmitToStream(); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(5665, "https://github.com/dotnet/roslyn/issues/5665")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerBogus(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule, parseOptions: parseOptions); //shouldn't have an error. The attribute's contents are checked when the module is added. var reference = other.EmitToImageReference(); s = @"class D {}"; other = CreateCompilation(s, new[] { reference }, TestOptions.SigningReleaseDll); // error CS7028: Error signing output with public key from container 'bogus' -- Keyset does not exist (Exception from HRESULT: 0x80090016) var err = other.GetDiagnostics().Single(); Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal("bogus", err.Arguments[0]); Assert.True(((string)err.Arguments[1]).EndsWith("0x80090016)", StringComparison.Ordinal), (string)err.Arguments[1]); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileBogus(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); //shouldn't have an error. The attribute's contents are checked when the module is added. var reference = other.EmitToImageReference(); s = @"class D {}"; other = CreateCompilation(s, new[] { reference }, TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("bogus", CodeAnalysisResources.FileNotFound)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AttemptToStrongNameWithOnlyPublicKey(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseDll.WithCryptoKeyFile(PublicKeyFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var refStrm = new MemoryStream(); var success = other.Emit(outStrm, metadataPEStream: refStrm); Assert.False(success.Success); // The diagnostic contains a random file path, so just check the code. Assert.True(success.Diagnostics[0].Code == (int)ErrorCode.ERR_SignButNoPrivateKey); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"); var other = CreateCompilation(s, options: options); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine_1(CSharpParseOptions parseOptions) { string s = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine_2(CSharpParseOptions parseOptions) { string s = @" [assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"), parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // error CS7091: Attribute 'System.Reflection.AssemblyKeyNameAttribute' given in a source file conflicts with option 'CryptoKeyContainer'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyNameAttribute", "CryptoKeyContainer") ); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void BothLegacyAndNonLegacyGiveTheSameOutput(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseDll .WithDeterministic(true) .WithModuleName("a.dll") .WithCryptoKeyFile(s_keyPairFile); var emitOptions = EmitOptions.Default.WithOutputNameOverride("a.dll"); var compilation = CreateCompilation(s, options: options, parseOptions: parseOptions); var stream = compilation.EmitToStream(emitOptions); stream.Position = 0; using (var metadata = AssemblyMetadata.CreateFromStream(stream)) { var key = metadata.GetAssembly().Identity.PublicKey; Assert.True(s_publicKey.SequenceEqual(key)); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignRefAssemblyKeyFileCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningDebugDll.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var refStrm = new MemoryStream(); var success = other.Emit(outStrm, metadataPEStream: refStrm); Assert.True(success.Success); outStrm.Position = 0; refStrm.Position = 0; Assert.True(ILValidation.IsStreamFullSigned(outStrm)); Assert.True(ILValidation.IsStreamFullSigned(refStrm)); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine_1(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var options = TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine_2(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // error CS7091: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyFileAttribute", "CryptoKeyFile")); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignItWithOnlyPublicKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile)); other = other.WithOptions(TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_publicKeyFile)); var assembly = CreateCompilation("", references: new[] { other.EmitToImageReference() }, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); assembly.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyOnNetModule(CSharpParseOptions parseOptions) { var other = CreateCompilation(@" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseModule, parseOptions: parseOptions); var comp = CreateCompilation("", references: new[] { other.EmitToImageReference() }, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.StartsWith("0024000004", ((SourceAssemblySymbol)comp.Assembly.Modules[1].ContainingAssembly).SignatureKey); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignItWithOnlyPublicKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile), parseOptions: parseOptions); using (var outStrm = new MemoryStream()) { var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignButNoKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); // Dev11: warning CS1699: Use command line option '/delaysign' or appropriate project settings instead of 'AssemblyDelaySignAttribute' // warning CS1607: Assembly generation -- Delay signing was requested, but no key was given // Roslyn: warning CS7033: Delay signing was specified and requires a public key, but no public key was specified other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_DelaySignButNoKey)); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignInMemory(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignConflict(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithDelaySign(false), parseOptions: parseOptions); var outStrm = new MemoryStream(); //shouldn't get any key warning. other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("DelaySign", "System.Reflection.AssemblyDelaySignAttribute")); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignNoConflict(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithDelaySign(true).WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); //shouldn't get any key warning. other.VerifyDiagnostics(); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignWithAssemblySignatureKey(CSharpParseOptions parseOptions) { DelaySignWithAssemblySignatureKeyHelper(); void DelaySignWithAssemblySignatureKeyHelper() { //Note that this SignatureKey is some random one that I found in the devdiv build. //It is not related to the other keys we use in these tests. //In the native compiler, when the AssemblySignatureKey attribute is present, and //the binary is configured for delay signing, the contents of the assemblySignatureKey attribute //(rather than the contents of the keyfile or container) are used to compute the size needed to //reserve in the binary for its signature. Signing using this key is only supported via sn.exe var options = TestOptions.SigningReleaseDll .WithDelaySign(true) .WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] [assembly: System.Reflection.AssemblySignatureKey(""002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3"", ""a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d"")] public class C { static void Goo() {} }", options: options, parseOptions: parseOptions); using (var metadata = ModuleMetadata.CreateFromImage(other.EmitToArray())) { var header = metadata.Module.PEReaderOpt.PEHeaders.CorHeader; //confirm header has expected SN signature size Assert.Equal(256, header.StrongNameSignatureDirectory.Size); // Delay sign should not have the strong name flag set Assert.Equal(CorFlags.ILOnly, header.Flags); } } } [WorkItem(545720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545720")] [WorkItem(530050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530050")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void InvalidAssemblyName(CSharpParseOptions parseOptions) { var il = @" .assembly extern mscorlib { } .assembly asm1 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 09 2F 5C 3A 2A 3F 27 3C 3E 7C 00 00 ) // .../\:*?'<>|.. } .class private auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var csharp = @" class Derived : Base { } "; var ilRef = CompileIL(il, prependDefaultHeader: false); var comp = CreateCompilation(csharp, new[] { ilRef }, assemblyName: "asm2", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); comp.VerifyDiagnostics( // NOTE: dev10 reports WRN_InvalidAssemblyName, but Roslyn won't (DevDiv #15099). // (2,17): error CS0122: 'Base' is inaccessible due to its protection level // class Derived : Base Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("Base").WithLocation(2, 17) ); } [WorkItem(546331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546331")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtualCall1(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] public class A { internal virtual void M() { } internal virtual int P { get { return 0; } } internal virtual event System.Action E { add { } remove { } } } "; var source2 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] public class B : A { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source3 = @" using System; using System.Linq.Expressions; public class C : B { internal override void M() { } void Test() { C c = new C(); c.M(); int x = c.P; c.E += null; } void TestET() { C c = new C(); Expression<Action> expr = () => c.M(); } } "; var comp1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib45(source2, new[] { ref1 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm2", parseOptions: parseOptions); comp2.VerifyDiagnostics(); var ref2 = new CSharpCompilationReference(comp2); var comp3 = CreateCompilationWithMscorlib45(source3, new[] { SystemCoreRef, ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics(); // Note: calls B.M, not A.M, since asm1 is not accessible. var verifier = CompileAndVerify(comp3); verifier.VerifyIL("C.Test", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: callvirt ""void B.M()"" IL_000b: dup IL_000c: callvirt ""int B.P.get"" IL_0011: pop IL_0012: ldnull IL_0013: callvirt ""void B.E.add"" IL_0018: ret }"); verifier.VerifyIL("C.TestET", @" { // Code size 85 (0x55) .maxstack 3 IL_0000: newobj ""C.<>c__DisplayClass2_0..ctor()"" IL_0005: dup IL_0006: newobj ""C..ctor()"" IL_000b: stfld ""C C.<>c__DisplayClass2_0.c"" IL_0010: ldtoken ""C.<>c__DisplayClass2_0"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001f: ldtoken ""C C.<>c__DisplayClass2_0.c"" IL_0024: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0029: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002e: ldtoken ""void B.M()"" IL_0033: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0038: castclass ""System.Reflection.MethodInfo"" IL_003d: ldc.i4.0 IL_003e: newarr ""System.Linq.Expressions.Expression"" IL_0043: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0048: ldc.i4.0 IL_0049: newarr ""System.Linq.Expressions.ParameterExpression"" IL_004e: call ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0053: pop IL_0054: ret } "); } [WorkItem(546331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546331")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtualCall2(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")] public class A { internal virtual void M() { } internal virtual int P { get { return 0; } } internal virtual event System.Action E { add { } remove { } } } "; var source2 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] public class B : A { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source3 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")] public class C : B { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source4 = @" using System; using System.Linq.Expressions; public class D : C { internal override void M() { } void Test() { D d = new D(); d.M(); int x = d.P; d.E += null; } void TestET() { D d = new D(); Expression<Action> expr = () => d.M(); } } "; var comp1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib45(source2, new[] { ref1 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm2", parseOptions: parseOptions); comp2.VerifyDiagnostics(); var ref2 = new CSharpCompilationReference(comp2); var comp3 = CreateCompilationWithMscorlib45(source3, new[] { ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics(); var ref3 = new CSharpCompilationReference(comp3); var comp4 = CreateCompilationWithMscorlib45(source4, new[] { SystemCoreRef, ref1, ref2, ref3 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm4", parseOptions: parseOptions); comp4.VerifyDiagnostics(); // Note: calls C.M, not A.M, since asm2 is not accessible (stops search). // Confirmed in Dev11. var verifier = CompileAndVerify(comp4); verifier.VerifyIL("D.Test", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: newobj ""D..ctor()"" IL_0005: dup IL_0006: callvirt ""void C.M()"" IL_000b: dup IL_000c: callvirt ""int C.P.get"" IL_0011: pop IL_0012: ldnull IL_0013: callvirt ""void C.E.add"" IL_0018: ret }"); verifier.VerifyIL("D.TestET", @" { // Code size 85 (0x55) .maxstack 3 IL_0000: newobj ""D.<>c__DisplayClass2_0..ctor()"" IL_0005: dup IL_0006: newobj ""D..ctor()"" IL_000b: stfld ""D D.<>c__DisplayClass2_0.d"" IL_0010: ldtoken ""D.<>c__DisplayClass2_0"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001f: ldtoken ""D D.<>c__DisplayClass2_0.d"" IL_0024: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0029: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002e: ldtoken ""void C.M()"" IL_0033: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0038: castclass ""System.Reflection.MethodInfo"" IL_003d: ldc.i4.0 IL_003e: newarr ""System.Linq.Expressions.Expression"" IL_0043: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0048: ldc.i4.0 IL_0049: newarr ""System.Linq.Expressions.ParameterExpression"" IL_004e: call ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0053: pop IL_0054: ret }"); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtual_ParamsAndDynamic(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] public class A { internal virtual void F(params int[] a) { } internal virtual void G(System.Action<dynamic> a) { } [System.Obsolete(""obsolete"", true)] internal virtual void H() { } internal virtual int this[int x, params int[] a] { get { return 0; } } } "; // use IL to generate code that doesn't have synthesized ParamArrayAttribute on int[] parameters: // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] // public class B : A // { // internal override void F(int[] a) { } // internal override void G(System.Action<object> a) { } // internal override void H() { } // internal override int this[int x, int[] a] { get { return 0; } } // } var source2 = @" .assembly extern asm1 { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly asm2 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 04 61 73 6D 33 00 00 ) // ...asm3.. } .class public auto ansi beforefieldinit B extends [asm1]A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method assembly hidebysig strict virtual instance void F(int32[] a) cil managed { nop ret } .method assembly hidebysig strict virtual instance void G(class [mscorlib]System.Action`1<object> a) cil managed { nop ret } .method assembly hidebysig strict virtual instance void H() cil managed { nop ret } .method assembly hidebysig specialname strict virtual instance int32 get_Item(int32 x, int32[] a) cil managed { ldloc.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [asm1]A::.ctor() ret } .property instance int32 Item(int32, int32[]) { .get instance int32 B::get_Item(int32, int32[]) } }"; var source3 = @" public class C : B { void Test() { C c = new C(); c.F(); c.G(x => x.Bar()); c.H(); var z = c[1]; } } "; var comp1 = CreateCompilation(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var ref2 = CompileIL(source2, prependDefaultHeader: false); var comp3 = CreateCompilation(source3, new[] { ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.F(int[])' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("a", "B.F(int[])").WithLocation(7, 11), // (8,20): error CS1061: 'object' does not contain a definition for 'Bar' and no extension method 'Bar' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Bar").WithArguments("object", "Bar").WithLocation(8, 20), // (10,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.this[int, int[]]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "c[1]").WithArguments("a", "B.this[int, int[]]").WithLocation(10, 17)); } [WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug529779_1(CSharpParseOptions parseOptions) { CSharpCompilation unsigned = CreateCompilation( @" public class C1 {} ", options: TestOptions.SigningReleaseDll, assemblyName: "Unsigned", parseOptions: parseOptions); CSharpCompilation other = CreateCompilation( @" public class C { internal void Goo() { var x = new System.Guid(); System.Console.WriteLine(x); } } ", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), new CSharpCompilationReference(unsigned) })).VerifyDiagnostics(); CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })).VerifyDiagnostics(); } [WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug529779_2(CSharpParseOptions parseOptions) { CSharpCompilation unsigned = CreateCompilation( @" public class C1 {} ", options: TestOptions.SigningReleaseDll, assemblyName: "Unsigned", parseOptions: parseOptions); CSharpCompilation other = CreateCompilation( @" public class C { internal void Goo() { var x = new C1(); System.Console.WriteLine(x); } } ", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var comps = new[] {other.WithReferences(new []{other.References.ElementAt(0), new CSharpCompilationReference(unsigned)}), other.WithReferences(new []{other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })}; foreach (var comp in comps) { var outStrm = new MemoryStream(); var emitResult = comp.Emit(outStrm); // Dev12 reports an error Assert.True(emitResult.Success); emitResult.Diagnostics.Verify( // warning CS8002: Referenced assembly 'Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. Diagnostic(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName).WithArguments("Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } } #if !NETCOREAPP [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] [WorkItem(399, "https://github.com/dotnet/roslyn/issues/399")] public void Bug399() { // The referenced assembly Signed.dll from the repro steps var signed = Roslyn.Test.Utilities.Desktop.DesktopRuntimeUtil.CreateMetadataReferenceFromHexGZipImage(@" 1f8b0800000000000400f38d9ac0c0ccc0c0c002c4ffff3330ec6080000706c2a00188f9e477f1316ce13cabb883d1e7ac62 484666b14241517e7a5162ae4272625e5e7e894252aa4251699e42669e828b7fb0426e7e4aaa1e2f2f970ad48c005706061f 4626869e0db74260e63e606052e466e486388a0922f64f094828c01d26006633419430302068860488f8790f06a0bf1c5a41 4a410841c32930580334d71f9f2781f6f11011161800e83e0e242e0790ef81c4d72b49ad2801b99b19a216d9af484624e815 a5e6e42743dde00055c386e14427729c08020f9420b407d86856860b404bef30323070a2a90b5080c4372120f781b1f3ada8 5ec1078b0a8f606f87dacdfeae3b162edb7de055d1af12c942bde5a267ef37e6c6b787945936b0ece367e8f6f87566c6f7bd 46a67f5da4f50d2f8a7e95e159552d1bf747b3ccdae1679c666dd10626bb1bf9815ad1c1876d04a76d78163e4b32a8a77fb3 a77adbec4d15c75de79cd9a3a4a5155dd1fc50b86ce5bd7797cce73b057b3931323082dd020ab332133d033d630363434b90 082b430e90ac0162e53a06861740da00c40e2e29cacc4b2f06a9906084c49b72683083022324ad28bb877aba80d402f96b40 7ca79cfc24a87f81d1c1c8ca000daf5faac60c620c60db41d1c408c50c0c5c509a012e0272e3425078c1792c0d0c48aa407a d41890d2355895288263e39b9f529a936ac7109c999e979aa2979293c3905b9c9c5f949399c4e0091184ca81d5332b80a9a9 8764e24b67aff2dff0feb1f6c7b7e6d50c1cdbab62c2244d1e74362c6000664a902ba600d5b1813c00e407053b1a821c0172 e1dddd9665aa576abb26acf9f6e2eaeaab7527ed1f49174726fc8f395ad7c676f650da9c159bbcd6a73cd031d8a9762d8d6b 47f9eac4955b0566f61fbc9010e4bbf0c405d6e6cc8392f63e6f4bc5339f2d9bb9725d79c0d5cecbacacc9af4522debeb30a bebd207fe9963cbbe995f66bb227ac4c0cfd91c3dce095617a66ce0e9d0b9e8eae9b25965c514278ff1dac3cc0021e2821f3 e29df38b5c72727c1333f32001949a0a0e2c10f8af0a344300ab2123052840cb16e30176c72818100000c85fc49900080000", filePath: "Signed.dll"); var compilation = CreateCompilation( "interface IDerived : ISigned { }", references: new[] { signed }, options: TestOptions.SigningReleaseDll .WithGeneralDiagnosticOption(ReportDiagnostic.Error) .WithCryptoKeyFile(s_keyPairFile)); // ACTUAL: error CS8002: Referenced assembly 'Signed, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. // EXPECTED: no errors compilation.VerifyEmitDiagnostics(); } #endif [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_1(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_2(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""")); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_3(CSharpParseOptions parseOptions) { var source = @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }"; var options = TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile); var other = CreateEmptyCompilation(source, options: options, references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var result = other.Emit(outStrm); Assert.False(result.Success); result.Diagnostics.VerifyErrorCodes( // error CS7027: Error signing output with public key from file 'KeyPairFile.snk' -- Invalid countersignature specified in AssemblySignatureKeyAttribute. (Exception from HRESULT: 0x80131423) Diagnostic(ErrorCode.ERR_PublicKeyFileFailure)); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_4(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""") ); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_5(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_6(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( null, ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // null, Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, "null") ); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_7(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", null)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } } [WorkItem(781312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781312")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug781312(CSharpParseOptions parseOptions) { var ca = CreateCompilation( @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Bug781312_B, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100458a131798af87d9e33088a3ab1c6101cbd462760f023d4f41d97f691033649e60b42001e94f4d79386b5e087b0a044c54b7afce151b3ad19b33b332b83087e3b8b022f45b5e4ff9b9a1077b0572ff0679ce38f884c7bd3d9b4090e4a7ee086b7dd292dc20f81a3b1b8a0b67ee77023131e59831c709c81d11c6856669974cc4"")] internal class A { public int Value = 3; } ", options: TestOptions.SigningReleaseDll, assemblyName: "Bug769840_A", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation( @" internal class B { public A GetA() { return new A(); } }", options: TestOptions.SigningReleaseModule, assemblyName: "Bug781312_B", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, verify: Verification.Fails).Diagnostics.Verify(); } [WorkItem(1072350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072350")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1072350(CSharpParseOptions parseOptions) { const string sourceA = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""X "")] internal class A { internal static int I = 42; }"; const string sourceB = @" class B { static void Main() { System.Console.Write(A.I); } }"; var ca = CreateCompilation(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, expectedOutput: "42").Diagnostics.Verify(); } [WorkItem(1072339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072339")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1072339(CSharpParseOptions parseOptions) { const string sourceA = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""x"")] internal class A { internal static int I = 42; }"; const string sourceB = @" class B { static void Main() { System.Console.Write(A.I); } }"; var ca = CreateCompilation(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, expectedOutput: "42").Diagnostics.Verify(); } [WorkItem(1095618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095618")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1095618(CSharpParseOptions parseOptions) { const string source = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")]"; var ca = CreateCompilation(source, parseOptions: parseOptions); ca.VerifyDiagnostics( // (1,12): warning CS1700: Assembly reference 'System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000' is invalid and cannot be resolved // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000")] Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")").WithArguments("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000").WithLocation(1, 12)); var verifier = CompileAndVerify(ca, symbolValidator: module => { var assembly = module.ContainingAssembly; Assert.NotNull(assembly); Assert.False(assembly.GetAttributes().Any(attr => attr.IsTargetAttribute(assembly, AttributeDescription.InternalsVisibleToAttribute))); }); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingNullKeyFile(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll; Assert.Null(options.CryptoKeyFile); var compilation = CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics(); VerifySignedBitSetAfterEmit(compilation, expectedToBeSigned: false); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithCryptoKeyFile(string.Empty); var compilation = CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics(); VerifySignedBitSetAfterEmit(compilation, expectedToBeSigned: false); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingNullKeyFile_PublicSign(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithPublicSign(true); Assert.Null(options.CryptoKeyFile); CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithCryptoKeyFile(string.Empty).WithPublicSign(true); CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasCOMInterop)] public void LegacyDoesNotUseBuilder() { var provider = new TestDesktopStrongNameProvider(fileSystem: new VirtualizedStrongNameFileSystem()) { SignBuilderFunc = delegate { throw null; } }; var options = TestOptions.ReleaseDll .WithStrongNameProvider(provider) .WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation( @" public class C { static void Goo() {} }", options: options, parseOptions: TestOptions.RegularWithLegacyStrongName); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } #endregion [Theory] [MemberData(nameof(AllProviderParseOptions))] [WorkItem(1341051, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1341051")] public void IVT_Circularity(CSharpParseOptions parseOptions) { string lib_cs = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public abstract class TestBaseClass { protected internal virtual bool SupportSvgImages { get; } } "; var libRef = CreateCompilation(lib_cs, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions).EmitToImageReference(); string source1 = @" [assembly: Class1] "; string source2 = @" public class Class1 : TestBaseClass { protected internal override bool SupportSvgImages { get { return true; } } } "; // To find what the property overrides, an IVT check is involved so we need to bind assembly-level attributes var c2 = CreateCompilation(new[] { source1, source2 }, new[] { libRef }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); c2.VerifyEmitDiagnostics( // (2,12): error CS0616: 'Class1' is not an attribute class // [assembly: Class1] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Class1").WithArguments("Class1").WithLocation(2, 12) ); } [Fact, WorkItem(1341051, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1341051")] public void IVT_Circularity_AttributeReferencesProperty() { string lib_cs = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public abstract class TestBaseClass { protected internal virtual bool SupportSvgImages { get; } } public class MyAttribute : System.Attribute { public MyAttribute(string s) { } } "; var libRef = CreateCompilation(lib_cs, options: TestOptions.SigningReleaseDll).EmitToImageReference(); string source1 = @" [assembly: MyAttribute(Class1.Constant)] "; string source2 = @" public class Class1 : TestBaseClass { internal const string Constant = ""text""; protected internal override bool SupportSvgImages { get { return true; } } } "; // To find what the property overrides, an IVT check is involved so we need to bind assembly-level attributes var c2 = CreateCompilation(new[] { source1, source2 }, new[] { libRef }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll); c2.VerifyEmitDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.SigningTestHelpers; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class InternalsVisibleToAndStrongNameTests : CSharpTestBase { public static IEnumerable<object[]> AllProviderParseOptions { get { if (ExecutionConditionUtil.IsWindows) { return new[] { new object[] { TestOptions.Regular }, new object[] { TestOptions.RegularWithLegacyStrongName } }; } return SpecializedCollections.SingletonEnumerable(new object[] { TestOptions.Regular }); } } #region Helpers public InternalsVisibleToAndStrongNameTests() { SigningTestHelpers.InstallKey(); } private static readonly string s_keyPairFile = SigningTestHelpers.KeyPairFile; private static readonly string s_publicKeyFile = SigningTestHelpers.PublicKeyFile; private static readonly ImmutableArray<byte> s_publicKey = SigningTestHelpers.PublicKey; private static StrongNameProvider GetProviderWithPath(string keyFilePath) => new DesktopStrongNameProvider(ImmutableArray.Create(keyFilePath), strongNameFileSystem: new VirtualizedStrongNameFileSystem()); #endregion #region Naming Tests [WorkItem(529419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529419")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblyKeyFileAttributeNotExistFile(CSharpParseOptions parseOptions) { string source = @" using System; using System.Reflection; [assembly: AssemblyKeyFile(""MyKey.snk"")] [assembly: AssemblyKeyName(""Key Name"")] public class Test { public static void Main() { Console.Write(""Hello World!""); } } "; // Dev11 RC gives error now (CS1548) + two warnings // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keyfile", "AssemblyKeyFile"), // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keycontainer", "AssemblyKeyName") var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()), parseOptions: parseOptions); c.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("MyKey.snk", CodeAnalysisResources.FileNotFound)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); CompileAndVerify(other, symbolValidator: (ModuleSymbol m) => { bool haveAttribute = false; foreach (var attrData in m.ContainingAssembly.GetAttributes()) { if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyFileAttribute)) { haveAttribute = true; break; } } Assert.True(haveAttribute); }); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = string.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", parseOptions); // verify failure with default assembly key file resolver var comp = CreateCompilation(syntaxTree, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, "Assembly signing not supported.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(keyFileDir))); comp.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestHasWindowsPaths)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver_RelativeToCurrentParent(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", parseOptions); // verify failure with default assembly key file resolver var comp = CreateCompilation(syntaxTree, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file '..\KeyPairFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(@"..\" + keyFileName, "Assembly signing not supported.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir\TempSubDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\")))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestHasWindowsPaths)] public void SigningNotAvailable001() { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", TestOptions.RegularWithLegacyStrongName); var provider = new TestDesktopStrongNameProvider( ImmutableArray.Create(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\")), new VirtualizedStrongNameFileSystem()) { GetStrongNameInterfaceFunc = () => throw new DllNotFoundException("aaa.dll not found.") }; var options = TestOptions.ReleaseDll.WithStrongNameProvider(provider); // verify failure var comp = CreateCompilation( assemblyName: GetUniqueName(), source: new[] { syntaxTree }, options: options); comp.VerifyEmitDiagnostics( // error CS7027: Error signing output with public key from file '..\KeyPair_6187d0d6-f691-47fd-985b-03570bc0668d.snk' -- aaa.dll not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("..\\" + keyFileName, "aaa.dll not found.").WithLocation(1, 1) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyContainerAttribute(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); CompileAndVerify(other, symbolValidator: (ModuleSymbol m) => { bool haveAttribute = false; foreach (var attrData in m.ContainingAssembly.GetAttributes()) { if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyNameAttribute)) { haveAttribute = true; break; } } Assert.True(haveAttribute); }); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptions_ReferenceResolver(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = "public class C {}"; var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default resolver var comp = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(keyFileName), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file 'KeyPairFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, CodeAnalysisResources.FileNotFound)); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(GetProviderWithPath(keyFileDir))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptionsJustPublicKey(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(TestResources.General.snPublicKey.AsImmutableOrNull(), other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptionsJustPublicKey_ReferenceResolver(CSharpParseOptions parseOptions) { string publicKeyFileDir = Path.GetDirectoryName(s_publicKeyFile); string publicKeyFileName = Path.GetFileName(s_publicKeyFile); string s = "public class C {}"; var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default resolver var comp = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file 'PublicKeyFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(publicKeyFileName, CodeAnalysisResources.FileNotFound), // warning CS7033: Delay signing was specified and requires a public key, but no public key was specified Diagnostic(ErrorCode.WRN_DelaySignButNoKey) ); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with publicKeyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true).WithStrongNameProvider(GetProviderWithPath(publicKeyFileDir))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFileNotFoundOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile("goo"), parseOptions: parseOptions); other.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("goo", CodeAnalysisResources.FileNotFound)); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFileBogusOptions(CSharpParseOptions parseOptions) { var tempFile = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4 }); string s = "public class C {}"; CSharpCompilation other = CreateCompilation(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(tempFile.Path), parseOptions: parseOptions); //TODO check for specific error Assert.NotEmpty(other.GetDiagnostics()); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [WorkItem(5662, "https://github.com/dotnet/roslyn/issues/5662")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyContainerBogusOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyContainer("goo"), parseOptions: parseOptions); // error CS7028: Error signing output with public key from container 'goo' -- Keyset does not exist (Exception from HRESULT: 0x80090016) var err = other.GetDiagnostics().Single(); Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal("goo", err.Arguments[0]); Assert.True(((string)err.Arguments[1]).EndsWith("0x80090016)", StringComparison.Ordinal), (string)err.Arguments[1]); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileAttributeOptionConflict(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyFile", "System.Reflection.AssemblyKeyFileAttribute")); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerAttributeOptionConflict(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyContainer("RoslynTestContainer"), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyContainer", "System.Reflection.AssemblyKeyNameAttribute")); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileAttributeEmpty(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile("""")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); other.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerEmpty(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName("""")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); other.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_DelaySigned(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C {}"; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey), parseOptions: parseOptions); c.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)); var metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()); var identity = metadata.Module.ReadAssemblyIdentityOrThrow(); Assert.True(identity.HasPublicKey); AssertEx.Equal(identity.PublicKey, s_publicKey); Assert.Equal(CorFlags.ILOnly, metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_PublicSign(CSharpParseOptions parseOptions) { // attributes are ignored string source = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] [assembly: System.Reflection.AssemblyKeyFile(""some file"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyNameAttribute").WithLocation(1, 1), // warning CS7103: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyFileAttribute").WithLocation(1, 1) ); Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)); var metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()); var identity = metadata.Module.ReadAssemblyIdentityOrThrow(); Assert.True(identity.HasPublicKey); AssertEx.Equal(identity.PublicKey, s_publicKey); Assert.Equal(CorFlags.ILOnly | CorFlags.StrongNameSigned, metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags); c = CreateCompilation(source, options: TestOptions.SigningReleaseModule.WithCryptoPublicKey(s_publicKey).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); c = CreateCompilation(source, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_publicKeyFile).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS7091: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyFileAttribute", "CryptoKeyFile").WithLocation(1, 1), // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); string source1 = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] [assembly: System.Reflection.AssemblyKeyFile(@""" + snk.Path + @""")] public class C {} "; c = CreateCompilation(source1, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(snk.Path).WithPublicSign(true)); c.VerifyDiagnostics( // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileFromAttributes_PublicSign(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyKeyFile(""test.snk"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyFileAttribute").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); Assert.True(c.Options.PublicSign); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerFromAttributes_PublicSign(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyNameAttribute").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); Assert.True(c.Options.PublicSign); } private void VerifySignedBitSetAfterEmit(Compilation comp, bool expectedToBeSigned = true) { using (var outStream = comp.EmitToStream()) { outStream.Position = 0; using (var reader = new PEReader(outStream)) { var flags = reader.PEHeaders.CorHeader.Flags; Assert.Equal(expectedToBeSigned, flags.HasFlag(CorFlags.StrongNameSigned)); } } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SnkFile_PublicSign(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C{}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(snk.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFile_PublicSign(CSharpParseOptions parseOptions) { var pubKeyFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(pubKeyFile.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSign_DelaySignAttribute(CSharpParseOptions parseOptions) { var pubKeyFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey); var comp = CreateCompilation(@" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(pubKeyFile.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // warning CS1616: Option 'PublicSign' overrides attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file or added module Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("PublicSign", "System.Reflection.AssemblyDelaySignAttribute").WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerNoSNProvider_PublicSign(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyContainer("roslynTestContainer") .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "CryptoKeyContainer").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerDesktopProvider_PublicSign(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.SigningReleaseDll .WithCryptoKeyContainer("roslynTestContainer") .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "CryptoKeyContainer").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyContainer); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignAndDelaySign(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithPublicSign(true) .WithDelaySign(true) .WithCryptoKeyFile(snk.Path), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'DelaySign' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "DelaySign").WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.True(comp.Options.DelaySign); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignAndDelaySignFalse(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithPublicSign(true) .WithDelaySign(false) .WithCryptoKeyFile(snk.Path), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.False(comp.Options.DelaySign); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignNoKey(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.True(comp.Assembly.PublicKey.IsDefaultOrEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_InvalidCompilationOptions(CSharpParseOptions parseOptions) { string source = @"public class C {}"; var c = CreateCompilation(source, options: TestOptions.SigningReleaseDll. WithCryptoPublicKey(ImmutableArray.Create<byte>(1, 2, 3)). WithCryptoKeyContainer("roslynTestContainer"). WithCryptoKeyFile("file.snk"), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS7102: Compilation options 'CryptoPublicKey' and 'CryptoKeyFile' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("CryptoPublicKey", "CryptoKeyFile").WithLocation(1, 1), // error CS7102: Compilation options 'CryptoPublicKey' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("CryptoPublicKey", "CryptoKeyContainer").WithLocation(1, 1), // error CS7088: Invalid 'CryptoPublicKey' value: '01-02-03'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("CryptoPublicKey", "01-02-03").WithLocation(1, 1)); } #endregion #region IVT Access Checking [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTBasicCompilation(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, assemblyName: "Paul", parseOptions: parseOptions); var c = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { new CSharpCompilationReference(other) }, assemblyName: "WantsIVTAccessButCantHave", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //compilation should not succeed, and internals should not be imported. c.VerifyDiagnostics( // (7,15): error CS0122: 'C.Goo()' is inaccessible due to its protection level // o.Goo(); Diagnostic(ErrorCode.ERR_BadAccess, "Goo").WithArguments("C.Goo()").WithLocation(7, 15) ); var c2 = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { new CSharpCompilationReference(other) }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll); Assert.Empty(c2.GetDiagnostics()); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTBasicMetadata(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public class C { internal void Goo() {} }"; var otherStream = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions).EmitToStream(); var c = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { AssemblyMetadata.CreateFromStream(otherStream, leaveOpen: true).GetReference() }, assemblyName: "WantsIVTAccessButCantHave", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //compilation should not succeed, and internals should not be imported. c.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Goo").WithArguments("C", "Goo")); otherStream.Position = 0; var c2 = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { MetadataReference.CreateFromStream(otherStream) }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.Empty(c2.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTSigned(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll.WithCryptoKeyContainer("roslynTestContainer"), assemblyName: "John", parseOptions: parseOptions); Assert.Empty(requestor.GetDiagnostics()); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNotBothSigned_CStoCS(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); // We allow John to access Paul's internal Goo even though strong-named John should not be referencing weak-named Paul. // Paul has, after all, specifically granted access to John. // During emit time we should produce an error that says that a strong-named assembly cannot reference // a weak-named assembly. But the C# compiler doesn't currently do that. See https://github.com/dotnet/roslyn/issues/26722 requestor.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void CS0281Method(CSharpParseOptions parseOptions) { var friendClass = CreateCompilation(@" using System.Runtime.CompilerServices; [ assembly: InternalsVisibleTo(""cs0281, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"") ] public class PublicClass { internal static void InternalMethod() { } protected static void ProtectedMethod() { } private static void PrivateMethod() { } internal protected static void InternalProtectedMethod() { } private protected static void PrivateProtectedMethod() { } }", assemblyName: "Paul", parseOptions: parseOptions); string cs0281 = @" public class Test { static void Main () { PublicClass.InternalMethod(); PublicClass.ProtectedMethod(); PublicClass.PrivateMethod(); PublicClass.InternalProtectedMethod(); PublicClass.PrivateProtectedMethod(); } }"; var other = CreateCompilation(cs0281, references: new[] { friendClass.EmitToImageReference() }, assemblyName: "cs0281", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics( // (7,15): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.InternalMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "InternalMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(7, 15), // (8,21): error CS0122: 'PublicClass.ProtectedMethod()' is inaccessible due to its protection level // PublicClass.ProtectedMethod(); Diagnostic(ErrorCode.ERR_BadAccess, "ProtectedMethod").WithArguments("PublicClass.ProtectedMethod()").WithLocation(8, 21), // (9,21): error CS0117: 'PublicClass' does not contain a definition for 'PrivateMethod' // PublicClass.PrivateMethod(); Diagnostic(ErrorCode.ERR_NoSuchMember, "PrivateMethod").WithArguments("PublicClass", "PrivateMethod").WithLocation(9, 21), // (10,21): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.InternalProtectedMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "InternalProtectedMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(10, 21), // (11,21): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.PrivateProtectedMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "PrivateProtectedMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(11, 21) ); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void CS0281Class(CSharpParseOptions parseOptions) { var friendClass = CreateCompilation(@" using System.Runtime.CompilerServices; [ assembly: InternalsVisibleTo(""cs0281, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"") ] internal class FriendClass { public static void MyMethod() { } }", assemblyName: "Paul", parseOptions: parseOptions); string cs0281 = @" public class Test { static void Main () { FriendClass.MyMethod (); } }"; var other = CreateCompilation(cs0281, references: new[] { friendClass.EmitToImageReference() }, assemblyName: "cs0281", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); // (7, 3): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // FriendClass.MyMethod (); other.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "FriendClass").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(7, 3) ); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNotBothSigned_VBtoCS(CSharpParseOptions parseOptions) { string s = @"<assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")> Public Class C Friend Sub Goo() End Sub End Class"; var other = VisualBasic.VisualBasicCompilation.Create( syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(s) }, references: new[] { MscorlibRef_v4_0_30316_17626 }, assemblyName: "Paul", options: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithStrongNameProvider(DefaultDesktopStrongNameProvider)); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { MetadataReference.CreateFromImage(other.EmitToArray()) }, assemblyName: "John", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); // We allow John to access Paul's internal Goo even though strong-named John should not be referencing weak-named Paul. // Paul has, after all, specifically granted access to John. // During emit time we should produce an error that says that a strong-named assembly cannot reference // a weak-named assembly. But the C# compiler doesn't currently do that. See https://github.com/dotnet/roslyn/issues/26722 requestor.VerifyDiagnostics(); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredSuccess(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); Assert.Empty(requestor.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailSignMismatch(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //not signed. cryptoKeyFile: KeyPairFile, other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics(); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailSignMismatch_AssemblyKeyName(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //not signed. cryptoKeyFile: KeyPairFile, other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_FriendRefSigningMismatch, arguments: new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" })); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatch(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( // (2,12): error CS0122: 'CAttribute' is inaccessible due to its protection level // [assembly: C()] Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("CAttribute").WithLocation(2, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatch_AssemblyKeyName(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( // error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2', // but the public key of the output assembly ('John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis) .WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2") .WithLocation(1, 1), // (2,12): error CS0122: 'AssemblyKeyNameAttribute' is inaccessible due to its protection level // [assembly: AssemblyKeyName()] Diagnostic(ErrorCode.ERR_BadAccess, "AssemblyKeyName").WithArguments("AssemblyKeyNameAttribute").WithLocation(2, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTSuccessThroughIAssembly(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, options: TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.True(other.Assembly.GivesAccessTo(requestor.Assembly)); Assert.Empty(requestor.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatchIAssembly(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.False(other.Assembly.GivesAccessTo(requestor.Assembly)); requestor.VerifyDiagnostics( // (3,12): error CS0122: 'CAttribute' is inaccessible due to its protection level // [assembly: C()] Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("CAttribute").WithLocation(3, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatchIAssembly_AssemblyKeyName(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.False(other.Assembly.GivesAccessTo(requestor.Assembly)); requestor.VerifyDiagnostics( // error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2', // but the public key of the output assembly ('John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis) .WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2") .WithLocation(1, 1), // (3,12): error CS0122: 'AssemblyKeyNameAttribute' is inaccessible due to its protection level // [assembly: AssemblyKeyName()] Diagnostic(ErrorCode.ERR_BadAccess, "AssemblyKeyName").WithArguments("AssemblyKeyNameAttribute").WithLocation(3, 12) ); } [WorkItem(820450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820450")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTGivesAccessToUsingDifferentKeys(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] namespace ClassLibrary1 { internal class Class1 { } } "; var giver = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile2), parseOptions: parseOptions); giver.VerifyDiagnostics(); var requestor = CreateCompilation( @" namespace ClassLibrary2 { internal class A { public void Goo(ClassLibrary1.Class1 a) { } } }", new MetadataReference[] { new CSharpCompilationReference(giver) }, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "John", parseOptions: parseOptions); Assert.True(giver.Assembly.GivesAccessTo(requestor.Assembly)); Assert.Empty(requestor.GetDiagnostics()); } #endregion #region IVT instantiations [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTHasCulture(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")] public class C { static void Goo() {} } ", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")").WithArguments("WantsIVTAccess, Culture=neutral")); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNoKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""WantsIVTAccess"")] public class C { static void Main() {} } ", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblySNReq, @"InternalsVisibleTo(""WantsIVTAccess"")").WithArguments("WantsIVTAccess")); } #endregion #region Signing [ConditionalTheory(typeof(DesktopOnly), Reason = "https://github.com/dotnet/coreclr/issues/21723")] [MemberData(nameof(AllProviderParseOptions))] public void MaxSizeKey(CSharpParseOptions parseOptions) { var pubKey = TestResources.General.snMaxSizePublicKeyString; string pubKeyToken = "1540923db30520b2"; var pubKeyTokenBytes = new byte[] { 0x15, 0x40, 0x92, 0x3d, 0xb3, 0x05, 0x20, 0xb2 }; var comp = CreateCompilation($@" using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""MaxSizeComp2, PublicKey={pubKey}, PublicKeyToken={pubKeyToken}"")] internal class C {{ public static void M() {{ Console.WriteLine(""Called M""); }} }}", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); comp.VerifyEmitDiagnostics(); Assert.True(comp.IsRealSigned); VerifySignedBitSetAfterEmit(comp); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp.Assembly.Identity.PublicKeyToken); var src = @" class D { public static void Main() { C.M(); } }"; var comp2 = CreateCompilation(src, references: new[] { comp.ToMetadataReference() }, assemblyName: "MaxSizeComp2", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); CompileAndVerify(comp2, expectedOutput: "Called M"); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp2.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp2.Assembly.Identity.PublicKeyToken); var comp3 = CreateCompilation(src, references: new[] { comp.EmitToImageReference() }, assemblyName: "MaxSizeComp2", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); CompileAndVerify(comp3, expectedOutput: "Called M"); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp3.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp3.Assembly.Identity.PublicKeyToken); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignIt(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } private static bool IsFileFullSigned(TempFile file) { using (var metadata = new FileStream(file.Path, FileMode.Open)) { return ILValidation.IsStreamFullSigned(metadata); } } private void ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(MemoryStream moduleContents, AttributeDescription expectedModuleAttr, CSharpParseOptions parseOptions) { //a module doesn't get signed for real. It should have either a keyfile or keycontainer attribute //parked on a typeRef named 'AssemblyAttributesGoHere.' When the module is added to an assembly, the //resulting assembly is signed with the key referred to by the aforementioned attribute. EmitResult success; var tempFile = Temp.CreateFile(); moduleContents.Position = 0; using (var metadata = ModuleMetadata.CreateFromStream(moduleContents)) { var flags = metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags; //confirm file does not claim to be signed Assert.Equal(0, (int)(flags & CorFlags.StrongNameSigned)); var corlibName = RuntimeUtilities.IsCoreClrRuntime ? "netstandard" : "mscorlib"; EntityHandle token = metadata.Module.GetTypeRef(metadata.Module.GetAssemblyRef(corlibName), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var attrInfos = metadata.Module.FindTargetAttributes(token, expectedModuleAttr); Assert.Equal(1, attrInfos.Count()); var source = @" public class Z { }"; //now that the module checks out, ensure that adding it to a compilation outputting a dll //results in a signed assembly. var assemblyComp = CreateCompilation(source, new[] { metadata.GetReference() }, TestOptions.SigningReleaseDll, parseOptions: parseOptions); using (var finalStrm = tempFile.Open()) { success = assemblyComp.Emit(finalStrm); } } success.Diagnostics.Verify(); Assert.True(success.Success); Assert.True(IsFileFullSigned(tempFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileAttr(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); var outStrm = other.EmitToStream(); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerAttr(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); var outStrm = other.EmitToStream(); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(5665, "https://github.com/dotnet/roslyn/issues/5665")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerBogus(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule, parseOptions: parseOptions); //shouldn't have an error. The attribute's contents are checked when the module is added. var reference = other.EmitToImageReference(); s = @"class D {}"; other = CreateCompilation(s, new[] { reference }, TestOptions.SigningReleaseDll); // error CS7028: Error signing output with public key from container 'bogus' -- Keyset does not exist (Exception from HRESULT: 0x80090016) var err = other.GetDiagnostics().Single(); Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal("bogus", err.Arguments[0]); Assert.True(((string)err.Arguments[1]).EndsWith("0x80090016)", StringComparison.Ordinal), (string)err.Arguments[1]); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileBogus(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); //shouldn't have an error. The attribute's contents are checked when the module is added. var reference = other.EmitToImageReference(); s = @"class D {}"; other = CreateCompilation(s, new[] { reference }, TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("bogus", CodeAnalysisResources.FileNotFound)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AttemptToStrongNameWithOnlyPublicKey(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseDll.WithCryptoKeyFile(PublicKeyFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var refStrm = new MemoryStream(); var success = other.Emit(outStrm, metadataPEStream: refStrm); Assert.False(success.Success); // The diagnostic contains a random file path, so just check the code. Assert.True(success.Diagnostics[0].Code == (int)ErrorCode.ERR_SignButNoPrivateKey); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"); var other = CreateCompilation(s, options: options); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine_1(CSharpParseOptions parseOptions) { string s = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine_2(CSharpParseOptions parseOptions) { string s = @" [assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"), parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // error CS7091: Attribute 'System.Reflection.AssemblyKeyNameAttribute' given in a source file conflicts with option 'CryptoKeyContainer'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyNameAttribute", "CryptoKeyContainer") ); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void BothLegacyAndNonLegacyGiveTheSameOutput(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseDll .WithDeterministic(true) .WithModuleName("a.dll") .WithCryptoKeyFile(s_keyPairFile); var emitOptions = EmitOptions.Default.WithOutputNameOverride("a.dll"); var compilation = CreateCompilation(s, options: options, parseOptions: parseOptions); var stream = compilation.EmitToStream(emitOptions); stream.Position = 0; using (var metadata = AssemblyMetadata.CreateFromStream(stream)) { var key = metadata.GetAssembly().Identity.PublicKey; Assert.True(s_publicKey.SequenceEqual(key)); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignRefAssemblyKeyFileCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningDebugDll.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var refStrm = new MemoryStream(); var success = other.Emit(outStrm, metadataPEStream: refStrm); Assert.True(success.Success); outStrm.Position = 0; refStrm.Position = 0; Assert.True(ILValidation.IsStreamFullSigned(outStrm)); Assert.True(ILValidation.IsStreamFullSigned(refStrm)); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine_1(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var options = TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine_2(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // error CS7091: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyFileAttribute", "CryptoKeyFile")); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignItWithOnlyPublicKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile)); other = other.WithOptions(TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_publicKeyFile)); var assembly = CreateCompilation("", references: new[] { other.EmitToImageReference() }, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); assembly.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyOnNetModule(CSharpParseOptions parseOptions) { var other = CreateCompilation(@" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseModule, parseOptions: parseOptions); var comp = CreateCompilation("", references: new[] { other.EmitToImageReference() }, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.StartsWith("0024000004", ((SourceAssemblySymbol)comp.Assembly.Modules[1].ContainingAssembly).SignatureKey); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignItWithOnlyPublicKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile), parseOptions: parseOptions); using (var outStrm = new MemoryStream()) { var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignButNoKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); // Dev11: warning CS1699: Use command line option '/delaysign' or appropriate project settings instead of 'AssemblyDelaySignAttribute' // warning CS1607: Assembly generation -- Delay signing was requested, but no key was given // Roslyn: warning CS7033: Delay signing was specified and requires a public key, but no public key was specified other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_DelaySignButNoKey)); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignInMemory(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignConflict(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithDelaySign(false), parseOptions: parseOptions); var outStrm = new MemoryStream(); //shouldn't get any key warning. other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("DelaySign", "System.Reflection.AssemblyDelaySignAttribute")); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignNoConflict(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithDelaySign(true).WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); //shouldn't get any key warning. other.VerifyDiagnostics(); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignWithAssemblySignatureKey(CSharpParseOptions parseOptions) { DelaySignWithAssemblySignatureKeyHelper(); void DelaySignWithAssemblySignatureKeyHelper() { //Note that this SignatureKey is some random one that I found in the devdiv build. //It is not related to the other keys we use in these tests. //In the native compiler, when the AssemblySignatureKey attribute is present, and //the binary is configured for delay signing, the contents of the assemblySignatureKey attribute //(rather than the contents of the keyfile or container) are used to compute the size needed to //reserve in the binary for its signature. Signing using this key is only supported via sn.exe var options = TestOptions.SigningReleaseDll .WithDelaySign(true) .WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] [assembly: System.Reflection.AssemblySignatureKey(""002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3"", ""a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d"")] public class C { static void Goo() {} }", options: options, parseOptions: parseOptions); using (var metadata = ModuleMetadata.CreateFromImage(other.EmitToArray())) { var header = metadata.Module.PEReaderOpt.PEHeaders.CorHeader; //confirm header has expected SN signature size Assert.Equal(256, header.StrongNameSignatureDirectory.Size); // Delay sign should not have the strong name flag set Assert.Equal(CorFlags.ILOnly, header.Flags); } } } [WorkItem(545720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545720")] [WorkItem(530050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530050")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void InvalidAssemblyName(CSharpParseOptions parseOptions) { var il = @" .assembly extern mscorlib { } .assembly asm1 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 09 2F 5C 3A 2A 3F 27 3C 3E 7C 00 00 ) // .../\:*?'<>|.. } .class private auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var csharp = @" class Derived : Base { } "; var ilRef = CompileIL(il, prependDefaultHeader: false); var comp = CreateCompilation(csharp, new[] { ilRef }, assemblyName: "asm2", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); comp.VerifyDiagnostics( // NOTE: dev10 reports WRN_InvalidAssemblyName, but Roslyn won't (DevDiv #15099). // (2,17): error CS0122: 'Base' is inaccessible due to its protection level // class Derived : Base Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("Base").WithLocation(2, 17) ); } [WorkItem(546331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546331")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtualCall1(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] public class A { internal virtual void M() { } internal virtual int P { get { return 0; } } internal virtual event System.Action E { add { } remove { } } } "; var source2 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] public class B : A { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source3 = @" using System; using System.Linq.Expressions; public class C : B { internal override void M() { } void Test() { C c = new C(); c.M(); int x = c.P; c.E += null; } void TestET() { C c = new C(); Expression<Action> expr = () => c.M(); } } "; var comp1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib45(source2, new[] { ref1 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm2", parseOptions: parseOptions); comp2.VerifyDiagnostics(); var ref2 = new CSharpCompilationReference(comp2); var comp3 = CreateCompilationWithMscorlib45(source3, new[] { SystemCoreRef, ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics(); // Note: calls B.M, not A.M, since asm1 is not accessible. var verifier = CompileAndVerify(comp3); verifier.VerifyIL("C.Test", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: callvirt ""void B.M()"" IL_000b: dup IL_000c: callvirt ""int B.P.get"" IL_0011: pop IL_0012: ldnull IL_0013: callvirt ""void B.E.add"" IL_0018: ret }"); verifier.VerifyIL("C.TestET", @" { // Code size 85 (0x55) .maxstack 3 IL_0000: newobj ""C.<>c__DisplayClass2_0..ctor()"" IL_0005: dup IL_0006: newobj ""C..ctor()"" IL_000b: stfld ""C C.<>c__DisplayClass2_0.c"" IL_0010: ldtoken ""C.<>c__DisplayClass2_0"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001f: ldtoken ""C C.<>c__DisplayClass2_0.c"" IL_0024: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0029: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002e: ldtoken ""void B.M()"" IL_0033: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0038: castclass ""System.Reflection.MethodInfo"" IL_003d: ldc.i4.0 IL_003e: newarr ""System.Linq.Expressions.Expression"" IL_0043: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0048: ldc.i4.0 IL_0049: newarr ""System.Linq.Expressions.ParameterExpression"" IL_004e: call ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0053: pop IL_0054: ret } "); } [WorkItem(546331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546331")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtualCall2(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")] public class A { internal virtual void M() { } internal virtual int P { get { return 0; } } internal virtual event System.Action E { add { } remove { } } } "; var source2 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] public class B : A { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source3 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")] public class C : B { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source4 = @" using System; using System.Linq.Expressions; public class D : C { internal override void M() { } void Test() { D d = new D(); d.M(); int x = d.P; d.E += null; } void TestET() { D d = new D(); Expression<Action> expr = () => d.M(); } } "; var comp1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib45(source2, new[] { ref1 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm2", parseOptions: parseOptions); comp2.VerifyDiagnostics(); var ref2 = new CSharpCompilationReference(comp2); var comp3 = CreateCompilationWithMscorlib45(source3, new[] { ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics(); var ref3 = new CSharpCompilationReference(comp3); var comp4 = CreateCompilationWithMscorlib45(source4, new[] { SystemCoreRef, ref1, ref2, ref3 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm4", parseOptions: parseOptions); comp4.VerifyDiagnostics(); // Note: calls C.M, not A.M, since asm2 is not accessible (stops search). // Confirmed in Dev11. var verifier = CompileAndVerify(comp4); verifier.VerifyIL("D.Test", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: newobj ""D..ctor()"" IL_0005: dup IL_0006: callvirt ""void C.M()"" IL_000b: dup IL_000c: callvirt ""int C.P.get"" IL_0011: pop IL_0012: ldnull IL_0013: callvirt ""void C.E.add"" IL_0018: ret }"); verifier.VerifyIL("D.TestET", @" { // Code size 85 (0x55) .maxstack 3 IL_0000: newobj ""D.<>c__DisplayClass2_0..ctor()"" IL_0005: dup IL_0006: newobj ""D..ctor()"" IL_000b: stfld ""D D.<>c__DisplayClass2_0.d"" IL_0010: ldtoken ""D.<>c__DisplayClass2_0"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001f: ldtoken ""D D.<>c__DisplayClass2_0.d"" IL_0024: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0029: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002e: ldtoken ""void C.M()"" IL_0033: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0038: castclass ""System.Reflection.MethodInfo"" IL_003d: ldc.i4.0 IL_003e: newarr ""System.Linq.Expressions.Expression"" IL_0043: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0048: ldc.i4.0 IL_0049: newarr ""System.Linq.Expressions.ParameterExpression"" IL_004e: call ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0053: pop IL_0054: ret }"); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtual_ParamsAndDynamic(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] public class A { internal virtual void F(params int[] a) { } internal virtual void G(System.Action<dynamic> a) { } [System.Obsolete(""obsolete"", true)] internal virtual void H() { } internal virtual int this[int x, params int[] a] { get { return 0; } } } "; // use IL to generate code that doesn't have synthesized ParamArrayAttribute on int[] parameters: // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] // public class B : A // { // internal override void F(int[] a) { } // internal override void G(System.Action<object> a) { } // internal override void H() { } // internal override int this[int x, int[] a] { get { return 0; } } // } var source2 = @" .assembly extern asm1 { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly asm2 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 04 61 73 6D 33 00 00 ) // ...asm3.. } .class public auto ansi beforefieldinit B extends [asm1]A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method assembly hidebysig strict virtual instance void F(int32[] a) cil managed { nop ret } .method assembly hidebysig strict virtual instance void G(class [mscorlib]System.Action`1<object> a) cil managed { nop ret } .method assembly hidebysig strict virtual instance void H() cil managed { nop ret } .method assembly hidebysig specialname strict virtual instance int32 get_Item(int32 x, int32[] a) cil managed { ldloc.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [asm1]A::.ctor() ret } .property instance int32 Item(int32, int32[]) { .get instance int32 B::get_Item(int32, int32[]) } }"; var source3 = @" public class C : B { void Test() { C c = new C(); c.F(); c.G(x => x.Bar()); c.H(); var z = c[1]; } } "; var comp1 = CreateCompilation(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var ref2 = CompileIL(source2, prependDefaultHeader: false); var comp3 = CreateCompilation(source3, new[] { ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.F(int[])' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("a", "B.F(int[])").WithLocation(7, 11), // (8,20): error CS1061: 'object' does not contain a definition for 'Bar' and no extension method 'Bar' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Bar").WithArguments("object", "Bar").WithLocation(8, 20), // (10,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.this[int, int[]]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "c[1]").WithArguments("a", "B.this[int, int[]]").WithLocation(10, 17)); } [WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug529779_1(CSharpParseOptions parseOptions) { CSharpCompilation unsigned = CreateCompilation( @" public class C1 {} ", options: TestOptions.SigningReleaseDll, assemblyName: "Unsigned", parseOptions: parseOptions); CSharpCompilation other = CreateCompilation( @" public class C { internal void Goo() { var x = new System.Guid(); System.Console.WriteLine(x); } } ", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), new CSharpCompilationReference(unsigned) })).VerifyDiagnostics(); CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })).VerifyDiagnostics(); } [WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug529779_2(CSharpParseOptions parseOptions) { CSharpCompilation unsigned = CreateCompilation( @" public class C1 {} ", options: TestOptions.SigningReleaseDll, assemblyName: "Unsigned", parseOptions: parseOptions); CSharpCompilation other = CreateCompilation( @" public class C { internal void Goo() { var x = new C1(); System.Console.WriteLine(x); } } ", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var comps = new[] {other.WithReferences(new []{other.References.ElementAt(0), new CSharpCompilationReference(unsigned)}), other.WithReferences(new []{other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })}; foreach (var comp in comps) { var outStrm = new MemoryStream(); var emitResult = comp.Emit(outStrm); // Dev12 reports an error Assert.True(emitResult.Success); emitResult.Diagnostics.Verify( // warning CS8002: Referenced assembly 'Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. Diagnostic(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName).WithArguments("Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } } #if !NETCOREAPP [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] [WorkItem(399, "https://github.com/dotnet/roslyn/issues/399")] public void Bug399() { // The referenced assembly Signed.dll from the repro steps var signed = Roslyn.Test.Utilities.Desktop.DesktopRuntimeUtil.CreateMetadataReferenceFromHexGZipImage(@" 1f8b0800000000000400f38d9ac0c0ccc0c0c002c4ffff3330ec6080000706c2a00188f9e477f1316ce13cabb883d1e7ac62 484666b14241517e7a5162ae4272625e5e7e894252aa4251699e42669e828b7fb0426e7e4aaa1e2f2f970ad48c005706061f 4626869e0db74260e63e606052e466e486388a0922f64f094828c01d26006633419430302068860488f8790f06a0bf1c5a41 4a410841c32930580334d71f9f2781f6f11011161800e83e0e242e0790ef81c4d72b49ad2801b99b19a216d9af484624e815 a5e6e42743dde00055c386e14427729c08020f9420b407d86856860b404bef30323070a2a90b5080c4372120f781b1f3ada8 5ec1078b0a8f606f87dacdfeae3b162edb7de055d1af12c942bde5a267ef37e6c6b787945936b0ece367e8f6f87566c6f7bd 46a67f5da4f50d2f8a7e95e159552d1bf747b3ccdae1679c666dd10626bb1bf9815ad1c1876d04a76d78163e4b32a8a77fb3 a77adbec4d15c75de79cd9a3a4a5155dd1fc50b86ce5bd7797cce73b057b3931323082dd020ab332133d033d630363434b90 082b430e90ac0162e53a06861740da00c40e2e29cacc4b2f06a9906084c49b72683083022324ad28bb877aba80d402f96b40 7ca79cfc24a87f81d1c1c8ca000daf5faac60c620c60db41d1c408c50c0c5c509a012e0272e3425078c1792c0d0c48aa407a d41890d2355895288263e39b9f529a936ac7109c999e979aa2979293c3905b9c9c5f949399c4e0091184ca81d5332b80a9a9 8764e24b67aff2dff0feb1f6c7b7e6d50c1cdbab62c2244d1e74362c6000664a902ba600d5b1813c00e407053b1a821c0172 e1dddd9665aa576abb26acf9f6e2eaeaab7527ed1f49174726fc8f395ad7c676f650da9c159bbcd6a73cd031d8a9762d8d6b 47f9eac4955b0566f61fbc9010e4bbf0c405d6e6cc8392f63e6f4bc5339f2d9bb9725d79c0d5cecbacacc9af4522debeb30a bebd207fe9963cbbe995f66bb227ac4c0cfd91c3dce095617a66ce0e9d0b9e8eae9b25965c514278ff1dac3cc0021e2821f3 e29df38b5c72727c1333f32001949a0a0e2c10f8af0a344300ab2123052840cb16e30176c72818100000c85fc49900080000", filePath: "Signed.dll"); var compilation = CreateCompilation( "interface IDerived : ISigned { }", references: new[] { signed }, options: TestOptions.SigningReleaseDll .WithGeneralDiagnosticOption(ReportDiagnostic.Error) .WithCryptoKeyFile(s_keyPairFile)); // ACTUAL: error CS8002: Referenced assembly 'Signed, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. // EXPECTED: no errors compilation.VerifyEmitDiagnostics(); } #endif [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_1(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_2(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""")); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_3(CSharpParseOptions parseOptions) { var source = @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }"; var options = TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile); var other = CreateEmptyCompilation(source, options: options, references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var result = other.Emit(outStrm); Assert.False(result.Success); result.Diagnostics.VerifyErrorCodes( // error CS7027: Error signing output with public key from file 'KeyPairFile.snk' -- Invalid countersignature specified in AssemblySignatureKeyAttribute. (Exception from HRESULT: 0x80131423) Diagnostic(ErrorCode.ERR_PublicKeyFileFailure)); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_4(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""") ); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_5(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_6(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( null, ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // null, Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, "null") ); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_7(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", null)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } } [WorkItem(781312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781312")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug781312(CSharpParseOptions parseOptions) { var ca = CreateCompilation( @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Bug781312_B, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100458a131798af87d9e33088a3ab1c6101cbd462760f023d4f41d97f691033649e60b42001e94f4d79386b5e087b0a044c54b7afce151b3ad19b33b332b83087e3b8b022f45b5e4ff9b9a1077b0572ff0679ce38f884c7bd3d9b4090e4a7ee086b7dd292dc20f81a3b1b8a0b67ee77023131e59831c709c81d11c6856669974cc4"")] internal class A { public int Value = 3; } ", options: TestOptions.SigningReleaseDll, assemblyName: "Bug769840_A", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation( @" internal class B { public A GetA() { return new A(); } }", options: TestOptions.SigningReleaseModule, assemblyName: "Bug781312_B", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, verify: Verification.Fails).Diagnostics.Verify(); } [WorkItem(1072350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072350")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1072350(CSharpParseOptions parseOptions) { const string sourceA = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""X "")] internal class A { internal static int I = 42; }"; const string sourceB = @" class B { static void Main() { System.Console.Write(A.I); } }"; var ca = CreateCompilation(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, expectedOutput: "42").Diagnostics.Verify(); } [WorkItem(1072339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072339")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1072339(CSharpParseOptions parseOptions) { const string sourceA = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""x"")] internal class A { internal static int I = 42; }"; const string sourceB = @" class B { static void Main() { System.Console.Write(A.I); } }"; var ca = CreateCompilation(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, expectedOutput: "42").Diagnostics.Verify(); } [WorkItem(1095618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095618")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1095618(CSharpParseOptions parseOptions) { const string source = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")]"; var ca = CreateCompilation(source, parseOptions: parseOptions); ca.VerifyDiagnostics( // (1,12): warning CS1700: Assembly reference 'System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000' is invalid and cannot be resolved // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000")] Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")").WithArguments("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000").WithLocation(1, 12)); var verifier = CompileAndVerify(ca, symbolValidator: module => { var assembly = module.ContainingAssembly; Assert.NotNull(assembly); Assert.False(assembly.GetAttributes().Any(attr => attr.IsTargetAttribute(assembly, AttributeDescription.InternalsVisibleToAttribute))); }); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingNullKeyFile(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll; Assert.Null(options.CryptoKeyFile); var compilation = CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics(); VerifySignedBitSetAfterEmit(compilation, expectedToBeSigned: false); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithCryptoKeyFile(string.Empty); var compilation = CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics(); VerifySignedBitSetAfterEmit(compilation, expectedToBeSigned: false); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingNullKeyFile_PublicSign(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithPublicSign(true); Assert.Null(options.CryptoKeyFile); CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithCryptoKeyFile(string.Empty).WithPublicSign(true); CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasCOMInterop)] public void LegacyDoesNotUseBuilder() { var provider = new TestDesktopStrongNameProvider(fileSystem: new VirtualizedStrongNameFileSystem()) { SignBuilderFunc = delegate { throw null; } }; var options = TestOptions.ReleaseDll .WithStrongNameProvider(provider) .WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation( @" public class C { static void Goo() {} }", options: options, parseOptions: TestOptions.RegularWithLegacyStrongName); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } #endregion [Theory] [MemberData(nameof(AllProviderParseOptions))] [WorkItem(1341051, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1341051")] public void IVT_Circularity(CSharpParseOptions parseOptions) { string lib_cs = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public abstract class TestBaseClass { protected internal virtual bool SupportSvgImages { get; } } "; var libRef = CreateCompilation(lib_cs, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions).EmitToImageReference(); string source1 = @" [assembly: Class1] "; string source2 = @" public class Class1 : TestBaseClass { protected internal override bool SupportSvgImages { get { return true; } } } "; // To find what the property overrides, an IVT check is involved so we need to bind assembly-level attributes var c2 = CreateCompilation(new[] { source1, source2 }, new[] { libRef }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); c2.VerifyEmitDiagnostics( // (2,12): error CS0616: 'Class1' is not an attribute class // [assembly: Class1] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Class1").WithArguments("Class1").WithLocation(2, 12) ); } [Fact, WorkItem(1341051, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1341051")] public void IVT_Circularity_AttributeReferencesProperty() { string lib_cs = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public abstract class TestBaseClass { protected internal virtual bool SupportSvgImages { get; } } public class MyAttribute : System.Attribute { public MyAttribute(string s) { } } "; var libRef = CreateCompilation(lib_cs, options: TestOptions.SigningReleaseDll).EmitToImageReference(); string source1 = @" [assembly: MyAttribute(Class1.Constant)] "; string source2 = @" public class Class1 : TestBaseClass { internal const string Constant = ""text""; protected internal override bool SupportSvgImages { get { return true; } } } "; // To find what the property overrides, an IVT check is involved so we need to bind assembly-level attributes var c2 = CreateCompilation(new[] { source1, source2 }, new[] { libRef }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll); c2.VerifyEmitDiagnostics(); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Analyzers/Core/Analyzers/PopulateSwitch/AbstractPopulateSwitchDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchDiagnosticAnalyzer<TSwitchOperation, TSwitchSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSwitchOperation : IOperation where TSwitchSyntax : SyntaxNode { private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(AnalyzersResources.Add_missing_cases), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(AnalyzersResources.Populate_switch), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); protected AbstractPopulateSwitchDiagnosticAnalyzer(string diagnosticId, EnforceOnBuild enforceOnBuild) : base(diagnosticId, enforceOnBuild, option: null, s_localizableTitle, s_localizableMessage) { } #region Interface methods protected abstract OperationKind OperationKind { get; } protected abstract ICollection<ISymbol> GetMissingEnumMembers(TSwitchOperation operation); protected abstract bool HasDefaultCase(TSwitchOperation operation); protected abstract Location GetDiagnosticLocation(TSwitchSyntax switchBlock); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterOperationAction(AnalyzeOperation, OperationKind); private void AnalyzeOperation(OperationAnalysisContext context) { var switchOperation = (TSwitchOperation)context.Operation; if (switchOperation.Syntax is not TSwitchSyntax switchBlock) return; var tree = switchBlock.SyntaxTree; if (SwitchIsIncomplete(switchOperation, out var missingCases, out var missingDefaultCase) && !tree.OverlapsHiddenPosition(switchBlock.Span, context.CancellationToken)) { Debug.Assert(missingCases || missingDefaultCase); var properties = ImmutableDictionary<string, string?>.Empty .Add(PopulateSwitchStatementHelpers.MissingCases, missingCases.ToString()) .Add(PopulateSwitchStatementHelpers.MissingDefaultCase, missingDefaultCase.ToString()); #pragma warning disable CS8620 // Mismatch in nullability of 'properties' parameter and argument types - Parameter type for 'properties' has been updated to 'ImmutableDictionary<string, string?>?' in newer version of Microsoft.CodeAnalysis (3.7.x). var diagnostic = Diagnostic.Create( Descriptor, GetDiagnosticLocation(switchBlock), properties: properties, additionalLocations: new[] { switchBlock.GetLocation() }); #pragma warning restore CS8620 context.ReportDiagnostic(diagnostic); } } #endregion private bool SwitchIsIncomplete( TSwitchOperation operation, out bool missingCases, out bool missingDefaultCase) { var missingEnumMembers = GetMissingEnumMembers(operation); missingCases = missingEnumMembers.Count > 0; missingDefaultCase = !HasDefaultCase(operation); // The switch is incomplete if we're missing any cases or we're missing a default case. return missingDefaultCase || missingCases; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchDiagnosticAnalyzer<TSwitchOperation, TSwitchSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSwitchOperation : IOperation where TSwitchSyntax : SyntaxNode { private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(AnalyzersResources.Add_missing_cases), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(AnalyzersResources.Populate_switch), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); protected AbstractPopulateSwitchDiagnosticAnalyzer(string diagnosticId, EnforceOnBuild enforceOnBuild) : base(diagnosticId, enforceOnBuild, option: null, s_localizableTitle, s_localizableMessage) { } #region Interface methods protected abstract OperationKind OperationKind { get; } protected abstract ICollection<ISymbol> GetMissingEnumMembers(TSwitchOperation operation); protected abstract bool HasDefaultCase(TSwitchOperation operation); protected abstract Location GetDiagnosticLocation(TSwitchSyntax switchBlock); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterOperationAction(AnalyzeOperation, OperationKind); private void AnalyzeOperation(OperationAnalysisContext context) { var switchOperation = (TSwitchOperation)context.Operation; if (switchOperation.Syntax is not TSwitchSyntax switchBlock) return; var tree = switchBlock.SyntaxTree; if (SwitchIsIncomplete(switchOperation, out var missingCases, out var missingDefaultCase) && !tree.OverlapsHiddenPosition(switchBlock.Span, context.CancellationToken)) { Debug.Assert(missingCases || missingDefaultCase); var properties = ImmutableDictionary<string, string?>.Empty .Add(PopulateSwitchStatementHelpers.MissingCases, missingCases.ToString()) .Add(PopulateSwitchStatementHelpers.MissingDefaultCase, missingDefaultCase.ToString()); #pragma warning disable CS8620 // Mismatch in nullability of 'properties' parameter and argument types - Parameter type for 'properties' has been updated to 'ImmutableDictionary<string, string?>?' in newer version of Microsoft.CodeAnalysis (3.7.x). var diagnostic = Diagnostic.Create( Descriptor, GetDiagnosticLocation(switchBlock), properties: properties, additionalLocations: new[] { switchBlock.GetLocation() }); #pragma warning restore CS8620 context.ReportDiagnostic(diagnostic); } } #endregion private bool SwitchIsIncomplete( TSwitchOperation operation, out bool missingCases, out bool missingDefaultCase) { var missingEnumMembers = GetMissingEnumMembers(operation); missingCases = missingEnumMembers.Count > 0; missingDefaultCase = !HasDefaultCase(operation); // The switch is incomplete if we're missing any cases or we're missing a default case. return missingDefaultCase || missingCases; } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.NamespaceSymbolKey.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; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class NamespaceSymbolKey { // The containing symbol can be one of many things. // 1) Null when this is the global namespace for a compilation. // 2) The SymbolId for an assembly symbol if this is the global namespace for an // assembly. // 3) The SymbolId for a module symbol if this is the global namespace for a module. // 4) The SymbolId for the containing namespace symbol if this is not a global // namespace. public static void Create(INamespaceSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); if (symbol.ContainingNamespace != null) { visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingNamespace); } else { // A global namespace can either belong to a module or to a compilation. Debug.Assert(symbol.IsGlobalNamespace); switch (symbol.NamespaceKind) { case NamespaceKind.Module: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingModule); break; case NamespaceKind.Assembly: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingAssembly); break; case NamespaceKind.Compilation: visitor.WriteBoolean(true); visitor.WriteSymbolKey(null); break; default: throw new NotImplementedException(); } } } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString()!; var isCompilationGlobalNamespace = reader.ReadBoolean(); var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason); if (containingSymbolFailureReason != null) { failureReason = $"({nameof(EventSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})"; return default; } if (isCompilationGlobalNamespace) { failureReason = null; return new SymbolKeyResolution(reader.Compilation.GlobalNamespace); } using var result = PooledArrayBuilder<INamespaceSymbol>.GetInstance(); foreach (var container in containingSymbolResolution) { switch (container) { case IAssemblySymbol assembly: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(assembly.GlobalNamespace); break; case IModuleSymbol module: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(module.GlobalNamespace); break; case INamespaceSymbol namespaceSymbol: foreach (var member in namespaceSymbol.GetMembers(metadataName)) { if (member is INamespaceSymbol childNamespace) { result.AddIfNotNull(childNamespace); } } break; } } return CreateResolution(result, $"({nameof(NamespaceSymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class NamespaceSymbolKey { // The containing symbol can be one of many things. // 1) Null when this is the global namespace for a compilation. // 2) The SymbolId for an assembly symbol if this is the global namespace for an // assembly. // 3) The SymbolId for a module symbol if this is the global namespace for a module. // 4) The SymbolId for the containing namespace symbol if this is not a global // namespace. public static void Create(INamespaceSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteString(symbol.MetadataName); if (symbol.ContainingNamespace != null) { visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingNamespace); } else { // A global namespace can either belong to a module or to a compilation. Debug.Assert(symbol.IsGlobalNamespace); switch (symbol.NamespaceKind) { case NamespaceKind.Module: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingModule); break; case NamespaceKind.Assembly: visitor.WriteBoolean(false); visitor.WriteSymbolKey(symbol.ContainingAssembly); break; case NamespaceKind.Compilation: visitor.WriteBoolean(true); visitor.WriteSymbolKey(null); break; default: throw new NotImplementedException(); } } } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString()!; var isCompilationGlobalNamespace = reader.ReadBoolean(); var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason); if (containingSymbolFailureReason != null) { failureReason = $"({nameof(EventSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})"; return default; } if (isCompilationGlobalNamespace) { failureReason = null; return new SymbolKeyResolution(reader.Compilation.GlobalNamespace); } using var result = PooledArrayBuilder<INamespaceSymbol>.GetInstance(); foreach (var container in containingSymbolResolution) { switch (container) { case IAssemblySymbol assembly: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(assembly.GlobalNamespace); break; case IModuleSymbol module: Debug.Assert(metadataName == string.Empty); result.AddIfNotNull(module.GlobalNamespace); break; case INamespaceSymbol namespaceSymbol: foreach (var member in namespaceSymbol.GetMembers(metadataName)) { if (member is INamespaceSymbol childNamespace) { result.AddIfNotNull(childNamespace); } } break; } } return CreateResolution(result, $"({nameof(NamespaceSymbolKey)} '{metadataName}' not found)", out failureReason); } } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/CSharp/Impl/Interactive/xlf/Commands.vsct.fr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../Commands.vsct"> <body> <trans-unit id="cmdidCSharpInteractiveToolWindow|ButtonText"> <source>C# Interactive</source> <target state="translated">C# Interactive</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../Commands.vsct"> <body> <trans-unit id="cmdidCSharpInteractiveToolWindow|ButtonText"> <source>C# Interactive</source> <target state="translated">C# Interactive</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/Core/Portable/Symbols/Attributes/IMarshalAsAttributeTarget.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal interface IMarshalAsAttributeTarget { MarshalPseudoCustomAttributeData GetOrCreateData(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal interface IMarshalAsAttributeTarget { MarshalPseudoCustomAttributeData GetOrCreateData(); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/Core/Portable/ExternalAccess/UnitTesting/API/IUnitTestingSolutionCrawlerRegistrationServiceAccessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { [Obsolete] internal interface IUnitTestingSolutionCrawlerServiceAccessor : IWorkspaceService { void Reanalyze(Workspace workspace, IEnumerable<ProjectId> projectIds = null, IEnumerable<DocumentId> documentIds = null, bool highPriority = false); void AddAnalyzerProvider(IUnitTestingIncrementalAnalyzerProviderImplementation provider, UnitTestingIncrementalAnalyzerProviderMetadataWrapper metadata); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { [Obsolete] internal interface IUnitTestingSolutionCrawlerServiceAccessor : IWorkspaceService { void Reanalyze(Workspace workspace, IEnumerable<ProjectId> projectIds = null, IEnumerable<DocumentId> documentIds = null, bool highPriority = false); void AddAnalyzerProvider(IUnitTestingIncrementalAnalyzerProviderImplementation provider, UnitTestingIncrementalAnalyzerProviderMetadataWrapper metadata); } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Analyzers/CSharp/Analyzers/UseIndexOrRangeOperator/CSharpUseRangeOperatorDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { using static Helpers; /// <summary> /// <para>Analyzer that looks for several variants of code like <c>s.Slice(start, end - start)</c> and /// offers to update to <c>s[start..end]</c> or <c>s.Slice(start..end)</c>. In order to convert to the /// indexer, the type being called on needs a slice-like method that takes two ints, and returns /// an instance of the same type. It also needs a <c>Length</c>/<c>Count</c> property, as well as an indexer /// that takes a <see cref="T:System.Range"/> instance. In order to convert between methods, there need to be /// two overloads that are equivalent except that one takes two ints, and the other takes a /// <see cref="T:System.Range"/>.</para> /// /// <para>It is assumed that if the type follows this shape that it is well behaved and that this /// transformation will preserve semantics. If this assumption is not good in practice, we /// could always limit the feature to only work on an allow list of known safe types.</para> /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Required to avoid ambiguous reference warnings.")] internal partial class CSharpUseRangeOperatorDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { // public const string UseIndexer = nameof(UseIndexer); public const string ComputedRange = nameof(ComputedRange); public const string ConstantRange = nameof(ConstantRange); public CSharpUseRangeOperatorDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseRangeOperatorDiagnosticId, EnforceOnBuildValues.UseRangeOperator, CSharpCodeStyleOptions.PreferRangeOperator, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_range_operator), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources._0_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(compilationContext => { // We're going to be checking every invocation in the compilation. Cache information // we compute in this object so we don't have to continually recompute it. var infoCache = new InfoCache(compilationContext.Compilation); // The System.Range type is always required to offer this fix. if (infoCache.RangeType != null) { compilationContext.RegisterOperationAction( c => AnalyzeInvocation(c, infoCache), OperationKind.Invocation); } }); } private void AnalyzeInvocation( OperationAnalysisContext context, InfoCache infoCache) { var resultOpt = AnalyzeInvocation( (IInvocationOperation)context.Operation, infoCache, context.Options, context.CancellationToken); if (resultOpt == null) { return; } context.ReportDiagnostic(CreateDiagnostic(resultOpt.Value)); } public static Result? AnalyzeInvocation( IInvocationOperation invocation, InfoCache infoCache, AnalyzerOptions analyzerOptionsOpt, CancellationToken cancellationToken) { // Validate we're on a piece of syntax we expect. While not necessary for analysis, we // want to make sure we're on something the fixer will know how to actually fix. if (!(invocation.Syntax is InvocationExpressionSyntax invocationSyntax) || invocationSyntax.ArgumentList is null) { return null; } CodeStyleOption2<bool> option = null; if (analyzerOptionsOpt != null) { // Check if we're at least on C# 8, and that the user wants these operators. var syntaxTree = invocationSyntax.SyntaxTree; var parseOptions = (CSharpParseOptions)syntaxTree.Options; if (parseOptions.LanguageVersion < LanguageVersion.CSharp8) { return null; } option = analyzerOptionsOpt.GetOption(CSharpCodeStyleOptions.PreferRangeOperator, syntaxTree, cancellationToken); if (!option.Value) { return null; } } // look for `s.Slice(e1, end - e2)` or `s.Slice(e1)` if (invocation.Instance is null) { return null; } return invocation.Arguments.Length switch { 1 => AnalyzeOneArgumentInvocation(invocation, infoCache, invocationSyntax, option), 2 => AnalyzeTwoArgumentInvocation(invocation, infoCache, invocationSyntax, option), _ => null, }; } private static Result? AnalyzeOneArgumentInvocation( IInvocationOperation invocation, InfoCache infoCache, InvocationExpressionSyntax invocationSyntax, CodeStyleOption2<bool> option) { var targetMethod = invocation.TargetMethod; // We are dealing with a call like `.Substring(expr)`. // Ensure that there is an overload with signature like `Substring(int start, int length)` // and there is a suitable indexer to replace this with `[expr..]`. if (!infoCache.TryGetMemberInfoOneArgument(targetMethod, out var memberInfo)) { return null; } var startOperation = invocation.Arguments[0].Value; return new Result( ResultKind.Computed, option, invocation, invocationSyntax, targetMethod, memberInfo, op1: startOperation, op2: null); // The range will run to the end. } private static Result? AnalyzeTwoArgumentInvocation( IInvocationOperation invocation, InfoCache infoCache, InvocationExpressionSyntax invocationSyntax, CodeStyleOption2<bool> option) { // See if the call is to something slice-like. var targetMethod = invocation.TargetMethod; // Second arg needs to be a subtraction for: `end - e2`. Once we've seen that we have // that, try to see if we're calling into some sort of Slice method with a matching // indexer or overload if (!IsSubtraction(invocation.Arguments[1].Value, out var subtraction) || !infoCache.TryGetMemberInfo(targetMethod, out var memberInfo)) { return null; } var indexer = GetIndexer(targetMethod.ContainingType, infoCache.RangeType, targetMethod.ContainingType); // Need to make sure that if the target method is being written to, that the indexer returns a ref, is a read/write property, // or the syntax allows for the slice method to be run if (invocation.Syntax.IsLeftSideOfAnyAssignExpression() && indexer != null && IsWriteableIndexer(invocation, indexer)) { return null; } // See if we have: (start, end - start). Specifically where the start operation it the // same as the right side of the subtraction. var startOperation = invocation.Arguments[0].Value; if (CSharpSyntaxFacts.Instance.AreEquivalent(startOperation.Syntax, subtraction.RightOperand.Syntax)) { return new Result( ResultKind.Computed, option, invocation, invocationSyntax, targetMethod, memberInfo, startOperation, subtraction.LeftOperand); } // See if we have: (constant1, s.Length - constant2). The constants don't have to be // the same value. This will convert over to s[constant1..(constant - constant1)] if (IsConstantInt32(startOperation) && IsConstantInt32(subtraction.RightOperand) && IsInstanceLengthCheck(memberInfo.LengthLikeProperty, invocation.Instance, subtraction.LeftOperand)) { return new Result( ResultKind.Constant, option, invocation, invocationSyntax, targetMethod, memberInfo, startOperation, subtraction.RightOperand); } return null; } private Diagnostic CreateDiagnostic(Result result) { // Keep track of the invocation node var invocation = result.Invocation; var additionalLocations = ImmutableArray.Create( invocation.GetLocation()); // Mark the span under the two arguments to .Slice(..., ...) as what we will be // updating. var arguments = invocation.ArgumentList.Arguments; var location = Location.Create(invocation.SyntaxTree, TextSpan.FromBounds(arguments.First().SpanStart, arguments.Last().Span.End)); return DiagnosticHelper.Create( Descriptor, location, result.Option.Notification.Severity, additionalLocations, ImmutableDictionary<string, string>.Empty, result.SliceLikeMethod.Name); } private static bool IsConstantInt32(IOperation operation) => operation.ConstantValue.HasValue && operation.ConstantValue.Value is int; private static bool IsWriteableIndexer(IInvocationOperation invocation, IPropertySymbol indexer) { var refReturnMismatch = indexer.ReturnsByRef != invocation.TargetMethod.ReturnsByRef; var indexerIsReadWrite = indexer.IsWriteableFieldOrProperty(); return refReturnMismatch && !indexerIsReadWrite; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { using static Helpers; /// <summary> /// <para>Analyzer that looks for several variants of code like <c>s.Slice(start, end - start)</c> and /// offers to update to <c>s[start..end]</c> or <c>s.Slice(start..end)</c>. In order to convert to the /// indexer, the type being called on needs a slice-like method that takes two ints, and returns /// an instance of the same type. It also needs a <c>Length</c>/<c>Count</c> property, as well as an indexer /// that takes a <see cref="T:System.Range"/> instance. In order to convert between methods, there need to be /// two overloads that are equivalent except that one takes two ints, and the other takes a /// <see cref="T:System.Range"/>.</para> /// /// <para>It is assumed that if the type follows this shape that it is well behaved and that this /// transformation will preserve semantics. If this assumption is not good in practice, we /// could always limit the feature to only work on an allow list of known safe types.</para> /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] [SuppressMessage("Documentation", "CA1200:Avoid using cref tags with a prefix", Justification = "Required to avoid ambiguous reference warnings.")] internal partial class CSharpUseRangeOperatorDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { // public const string UseIndexer = nameof(UseIndexer); public const string ComputedRange = nameof(ComputedRange); public const string ConstantRange = nameof(ConstantRange); public CSharpUseRangeOperatorDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseRangeOperatorDiagnosticId, EnforceOnBuildValues.UseRangeOperator, CSharpCodeStyleOptions.PreferRangeOperator, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_range_operator), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources._0_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(compilationContext => { // We're going to be checking every invocation in the compilation. Cache information // we compute in this object so we don't have to continually recompute it. var infoCache = new InfoCache(compilationContext.Compilation); // The System.Range type is always required to offer this fix. if (infoCache.RangeType != null) { compilationContext.RegisterOperationAction( c => AnalyzeInvocation(c, infoCache), OperationKind.Invocation); } }); } private void AnalyzeInvocation( OperationAnalysisContext context, InfoCache infoCache) { var resultOpt = AnalyzeInvocation( (IInvocationOperation)context.Operation, infoCache, context.Options, context.CancellationToken); if (resultOpt == null) { return; } context.ReportDiagnostic(CreateDiagnostic(resultOpt.Value)); } public static Result? AnalyzeInvocation( IInvocationOperation invocation, InfoCache infoCache, AnalyzerOptions analyzerOptionsOpt, CancellationToken cancellationToken) { // Validate we're on a piece of syntax we expect. While not necessary for analysis, we // want to make sure we're on something the fixer will know how to actually fix. if (!(invocation.Syntax is InvocationExpressionSyntax invocationSyntax) || invocationSyntax.ArgumentList is null) { return null; } CodeStyleOption2<bool> option = null; if (analyzerOptionsOpt != null) { // Check if we're at least on C# 8, and that the user wants these operators. var syntaxTree = invocationSyntax.SyntaxTree; var parseOptions = (CSharpParseOptions)syntaxTree.Options; if (parseOptions.LanguageVersion < LanguageVersion.CSharp8) { return null; } option = analyzerOptionsOpt.GetOption(CSharpCodeStyleOptions.PreferRangeOperator, syntaxTree, cancellationToken); if (!option.Value) { return null; } } // look for `s.Slice(e1, end - e2)` or `s.Slice(e1)` if (invocation.Instance is null) { return null; } return invocation.Arguments.Length switch { 1 => AnalyzeOneArgumentInvocation(invocation, infoCache, invocationSyntax, option), 2 => AnalyzeTwoArgumentInvocation(invocation, infoCache, invocationSyntax, option), _ => null, }; } private static Result? AnalyzeOneArgumentInvocation( IInvocationOperation invocation, InfoCache infoCache, InvocationExpressionSyntax invocationSyntax, CodeStyleOption2<bool> option) { var targetMethod = invocation.TargetMethod; // We are dealing with a call like `.Substring(expr)`. // Ensure that there is an overload with signature like `Substring(int start, int length)` // and there is a suitable indexer to replace this with `[expr..]`. if (!infoCache.TryGetMemberInfoOneArgument(targetMethod, out var memberInfo)) { return null; } var startOperation = invocation.Arguments[0].Value; return new Result( ResultKind.Computed, option, invocation, invocationSyntax, targetMethod, memberInfo, op1: startOperation, op2: null); // The range will run to the end. } private static Result? AnalyzeTwoArgumentInvocation( IInvocationOperation invocation, InfoCache infoCache, InvocationExpressionSyntax invocationSyntax, CodeStyleOption2<bool> option) { // See if the call is to something slice-like. var targetMethod = invocation.TargetMethod; // Second arg needs to be a subtraction for: `end - e2`. Once we've seen that we have // that, try to see if we're calling into some sort of Slice method with a matching // indexer or overload if (!IsSubtraction(invocation.Arguments[1].Value, out var subtraction) || !infoCache.TryGetMemberInfo(targetMethod, out var memberInfo)) { return null; } var indexer = GetIndexer(targetMethod.ContainingType, infoCache.RangeType, targetMethod.ContainingType); // Need to make sure that if the target method is being written to, that the indexer returns a ref, is a read/write property, // or the syntax allows for the slice method to be run if (invocation.Syntax.IsLeftSideOfAnyAssignExpression() && indexer != null && IsWriteableIndexer(invocation, indexer)) { return null; } // See if we have: (start, end - start). Specifically where the start operation it the // same as the right side of the subtraction. var startOperation = invocation.Arguments[0].Value; if (CSharpSyntaxFacts.Instance.AreEquivalent(startOperation.Syntax, subtraction.RightOperand.Syntax)) { return new Result( ResultKind.Computed, option, invocation, invocationSyntax, targetMethod, memberInfo, startOperation, subtraction.LeftOperand); } // See if we have: (constant1, s.Length - constant2). The constants don't have to be // the same value. This will convert over to s[constant1..(constant - constant1)] if (IsConstantInt32(startOperation) && IsConstantInt32(subtraction.RightOperand) && IsInstanceLengthCheck(memberInfo.LengthLikeProperty, invocation.Instance, subtraction.LeftOperand)) { return new Result( ResultKind.Constant, option, invocation, invocationSyntax, targetMethod, memberInfo, startOperation, subtraction.RightOperand); } return null; } private Diagnostic CreateDiagnostic(Result result) { // Keep track of the invocation node var invocation = result.Invocation; var additionalLocations = ImmutableArray.Create( invocation.GetLocation()); // Mark the span under the two arguments to .Slice(..., ...) as what we will be // updating. var arguments = invocation.ArgumentList.Arguments; var location = Location.Create(invocation.SyntaxTree, TextSpan.FromBounds(arguments.First().SpanStart, arguments.Last().Span.End)); return DiagnosticHelper.Create( Descriptor, location, result.Option.Notification.Severity, additionalLocations, ImmutableDictionary<string, string>.Empty, result.SliceLikeMethod.Name); } private static bool IsConstantInt32(IOperation operation) => operation.ConstantValue.HasValue && operation.ConstantValue.Value is int; private static bool IsWriteableIndexer(IInvocationOperation invocation, IPropertySymbol indexer) { var refReturnMismatch = indexer.ReturnsByRef != invocation.TargetMethod.ReturnsByRef; var indexerIsReadWrite = indexer.IsWriteableFieldOrProperty(); return refReturnMismatch && !indexerIsReadWrite; } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Def/EditorConfigSettings/Formatting/ViewModel/FormattingViewModel.SettingsSnapshotFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Formatting.ViewModel { internal partial class FormattingViewModel { internal sealed class SettingsSnapshotFactory : SettingsSnapshotFactoryBase<FormattingSetting, SettingsEntriesSnapshot> { public SettingsSnapshotFactory(ISettingsProvider<FormattingSetting> data) : base(data) { } protected override SettingsEntriesSnapshot CreateSnapshot(ImmutableArray<FormattingSetting> data, int currentVersionNumber) => new(data, currentVersionNumber); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Formatting.ViewModel { internal partial class FormattingViewModel { internal sealed class SettingsSnapshotFactory : SettingsSnapshotFactoryBase<FormattingSetting, SettingsEntriesSnapshot> { public SettingsSnapshotFactory(ISettingsProvider<FormattingSetting> data) : base(data) { } protected override SettingsEntriesSnapshot CreateSnapshot(ImmutableArray<FormattingSetting> data, int currentVersionNumber) => new(data, currentVersionNumber); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Def/EditorConfigSettings/CodeStyle/View/ColumnDefinitions/CodeStyleSeverityColumnDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Windows; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.CodeStyle; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View.ColumnDefinitions { [Export(typeof(ITableColumnDefinition))] [Name(Severity)] internal class CodeStyleSeverityColumnDefinition : TableColumnDefinitionBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CodeStyleSeverityColumnDefinition() { } public override string Name => Severity; public override string DisplayName => ServicesVSResources.Severity; public override double MinWidth => 120; public override bool DefaultVisible => false; public override bool IsFilterable => false; public override bool IsSortable => false; public override bool TryCreateColumnContent(ITableEntryHandle entry, bool singleColumnView, out FrameworkElement? content) { if (!entry.TryGetValue(Severity, out CodeStyleSetting setting)) { content = null; return false; } var control = new CodeStyleSeverityControl(setting); content = control; return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using System.Windows; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; using static Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common.ColumnDefinitions.CodeStyle; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View.ColumnDefinitions { [Export(typeof(ITableColumnDefinition))] [Name(Severity)] internal class CodeStyleSeverityColumnDefinition : TableColumnDefinitionBase { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CodeStyleSeverityColumnDefinition() { } public override string Name => Severity; public override string DisplayName => ServicesVSResources.Severity; public override double MinWidth => 120; public override bool DefaultVisible => false; public override bool IsFilterable => false; public override bool IsSortable => false; public override bool TryCreateColumnContent(ITableEntryHandle entry, bool singleColumnView, out FrameworkElement? content) { if (!entry.TryGetValue(Severity, out CodeStyleSetting setting)) { content = null; return false; } var control = new CodeStyleSeverityControl(setting); content = control; return true; } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/UsingBlockHighlighter.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.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class UsingBlockHighlighter Inherits AbstractKeywordHighlighter(Of SyntaxNode) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken) Dim usingBlock = node.GetAncestor(Of UsingBlockSyntax)() If usingBlock Is Nothing Then Return End If With usingBlock highlights.Add(.UsingStatement.UsingKeyword.Span) highlights.Add(.EndUsingStatement.Span) End With 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.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class UsingBlockHighlighter Inherits AbstractKeywordHighlighter(Of SyntaxNode) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken) Dim usingBlock = node.GetAncestor(Of UsingBlockSyntax)() If usingBlock Is Nothing Then Return End If With usingBlock highlights.Add(.UsingStatement.UsingKeyword.Span) highlights.Add(.EndUsingStatement.Span) End With End Sub End Class End Namespace
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWithEvents.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 Imports Microsoft.CodeAnalysis.VisualBasic Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenWithEvents Inherits BasicTestBase <Fact> Public Sub SimpleWithEventsTest() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Imports System.Linq Module Program Dim WithEvents X As Object = "AA", y As New Object Sub Main(args As String()) Console.WriteLine(X) X() = 42 Console.WriteLine(X()) _Y = 123 Console.WriteLine(_Y) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ AA 42 123 ]]>).VerifyIL("Program.Main", <![CDATA[ { // Code size 70 (0x46) .maxstack 1 IL_0000: call "Function Program.get_X() As Object" IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000a: call "Sub System.Console.WriteLine(Object)" IL_000f: ldc.i4.s 42 IL_0011: box "Integer" IL_0016: call "Sub Program.set_X(Object)" IL_001b: call "Function Program.get_X() As Object" IL_0020: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0025: call "Sub System.Console.WriteLine(Object)" IL_002a: ldc.i4.s 123 IL_002c: box "Integer" IL_0031: stsfld "Program._y As Object" IL_0036: ldsfld "Program._y As Object" IL_003b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0040: call "Sub System.Console.WriteLine(Object)" IL_0045: ret } ]]>).Compilation End Sub <Fact> Public Sub StaticHandlesMe() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class Program Shared Event E1() Shared Sub Main(args As String()) RaiseEvent E1() End Sub Shared Sub goo() Handles MyClass.E1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled ]]>).VerifyIL("Program..cctor", <![CDATA[ { // Code size 18 (0x12) .maxstack 2 IL_0000: ldnull IL_0001: ldftn "Sub Program.goo()" IL_0007: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0011: ret } ]]>).Compilation End Sub <Fact> Public Sub StaticHandlesMeInBase() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System class Base Shared Event E1() shared sub raiser() RaiseEvent E1() end sub end class Class Program Inherits Base Shared Sub Main(args As String()) raiser End Sub Shared Sub goo() Handles MyClass.E1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled ]]>).VerifyIL("Program..cctor", <![CDATA[ { // Code size 18 (0x12) .maxstack 2 IL_0000: ldnull IL_0001: ldftn "Sub Program.goo()" IL_0007: newobj "Sub Base.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: call "Sub Base.add_E1(Base.E1EventHandler)" IL_0011: ret } ]]>).Compilation End Sub <Fact> Public Sub InstanceHandlesMe() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> imports system Class Program Event E1() Shared Sub Main(args As String()) Call (New Program).Raiser() End Sub Sub Raiser() RaiseEvent E1() End Sub Shared Sub goo() Handles MyClass.e1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled ]]>).VerifyIL("Program..ctor", <![CDATA[ { // Code size 25 (0x19) .maxstack 3 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldnull IL_0008: ldftn "Sub Program.goo()" IL_000e: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_0013: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0018: ret } ]]>).Compilation End Sub <Fact> Public Sub InstanceHandlesMeNeedCtor() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> imports system Class Program Event E1(x As Integer) Sub New() Me.New(42) End Sub Sub New(x As Integer) End Sub Sub New(x As Long) End Sub Shared Sub Main(args As String()) Call (New Program()).Raiser() End Sub Sub Raiser() RaiseEvent E1(123) End Sub Shared Sub goo() Handles MyClass.e1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled ]]>).VerifyIL("Program..ctor", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: call "Sub Program..ctor(Integer)" IL_0008: ret } ]]>).VerifyIL("Program..ctor(Integer)", <![CDATA[ { // Code size 49 (0x31) .maxstack 3 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler" IL_0013: br.s IL_002b IL_0015: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_001a: ldftn "Sub Program._Closure$__._Lambda$__R6-1(Integer)" IL_0020: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler" IL_002b: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0030: ret } ]]>).VerifyIL("Program..ctor(Long)", <![CDATA[ { // Code size 49 (0x31) .maxstack 3 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler" IL_0013: br.s IL_002b IL_0015: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_001a: ldftn "Sub Program._Closure$__._Lambda$__R7-2(Integer)" IL_0020: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler" IL_002b: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0030: ret } ]]>).Compilation End Sub <Fact> Public Sub InstanceHandlesMeMismatched() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option strict off Imports System Class base Event E2(ByRef x As Integer) Sub Raiser() RaiseEvent E2(123) End Sub End Class Class Program Inherits base Shared Event E1(x As Integer) Shared Sub Main(args As String()) Call (New Program).Raiser() End Sub Shadows Sub Raiser() RaiseEvent E1(123) MyBase.Raiser() End Sub Sub goo1() Handles MyClass.E1 Console.WriteLine("handled1") End Sub Shared Sub goo2() Handles MyClass.E2 Console.WriteLine("handled2") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled1 handled2 ]]>).VerifyIL("Program..ctor", <![CDATA[ { // Code size 66 (0x42) .maxstack 3 IL_0000: ldarg.0 IL_0001: call "Sub base..ctor()" IL_0006: ldarg.0 IL_0007: ldftn "Sub Program._Lambda$__R0-1(Integer)" IL_000d: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_0012: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0017: ldarg.0 IL_0018: ldsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler" IL_001d: brfalse.s IL_0026 IL_001f: ldsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler" IL_0024: br.s IL_003c IL_0026: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_002b: ldftn "Sub Program._Closure$__._Lambda$__R0-2(ByRef Integer)" IL_0031: newobj "Sub base.E2EventHandler..ctor(Object, System.IntPtr)" IL_0036: dup IL_0037: stsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler" IL_003c: call "Sub base.add_E2(base.E2EventHandler)" IL_0041: ret } ]]>).Compilation End Sub <Fact> Public Sub InstanceHandlesMeMismatchedStrict() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class base Event E2(ByRef x As Integer) Sub Raiser() RaiseEvent E2(123) End Sub End Class Class Program Inherits base Shared Event E1(x As Integer) Shared Sub Main(args As String()) Call (New Program).Raiser() End Sub Shadows Sub Raiser() RaiseEvent E1(123) MyBase.Raiser() End Sub Sub goo1() Handles MyClass.E1 Console.WriteLine("handled1") End Sub Shared Function goo2(arg As Long) As Integer Handles MyClass.E1 Console.WriteLine("handled2") Return 123 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[handled2 handled1 ]]>).VerifyIL("Program..ctor", <![CDATA[ { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub base..ctor()" IL_0006: ldarg.0 IL_0007: ldftn "Sub Program._Lambda$__R1-2(Integer)" IL_000d: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_0012: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0017: ret } ]]>).Compilation End Sub <Fact> Public Sub SimpleSharedWithEvents() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class cls1 Event E1() Sub raiser() RaiseEvent E1() End Sub End Class Class cls2 Shared WithEvents w As cls1 Public Shared Sub Main() Dim o As New cls1 o.raiser() w = o o.raiser() w = o o.raiser() w = Nothing o.raiser() End Sub Private Shared Sub handler() Handles w.E1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled handled ]]>).VerifyIL("cls2.set_w", <![CDATA[ { // Code size 52 (0x34) .maxstack 2 .locals init (cls1.E1EventHandler V_0, cls1 V_1) IL_0000: ldnull IL_0001: ldftn "Sub cls2.handler()" IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldsfld "cls2._w As cls1" IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: brfalse.s IL_001d IL_0016: ldloc.1 IL_0017: ldloc.0 IL_0018: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_001d: ldarg.0 IL_001e: stsfld "cls2._w As cls1" IL_0023: ldsfld "cls2._w As cls1" IL_0028: stloc.1 IL_0029: ldloc.1 IL_002a: brfalse.s IL_0033 IL_002c: ldloc.1 IL_002d: ldloc.0 IL_002e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_0033: ret } ]]>).Compilation End Sub <Fact> Public Sub SimpleInstanceWithEvents() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> imports system Class cls1 Event E1() Sub raiser() RaiseEvent E1() End Sub End Class Class cls2 WithEvents w As cls1 Public Sub Test() Dim o As New cls1 o.raiser() w = o o.raiser() w = o o.raiser() w = Nothing o.raiser() End Sub Public Shared Sub main() Call (New cls2).Test() End Sub Private Sub handler() Handles w.E1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled handled ]]>).VerifyIL("cls2.set_w", <![CDATA[ { // Code size 55 (0x37) .maxstack 2 .locals init (cls1.E1EventHandler V_0, cls1 V_1) IL_0000: ldarg.0 IL_0001: ldftn "Sub cls2.handler()" IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldarg.0 IL_000e: ldfld "cls2._w As cls1" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_001e IL_0017: ldloc.1 IL_0018: ldloc.0 IL_0019: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_001e: ldarg.0 IL_001f: ldarg.1 IL_0020: stfld "cls2._w As cls1" IL_0025: ldarg.0 IL_0026: ldfld "cls2._w As cls1" IL_002b: stloc.1 IL_002c: ldloc.1 IL_002d: brfalse.s IL_0036 IL_002f: ldloc.1 IL_0030: ldloc.0 IL_0031: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_0036: ret } ]]>).Compilation End Sub <Fact> Public Sub BaseInstanceWithEventsMultiple() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class cls1 Event E1(x As Integer) Sub raiser() RaiseEvent E1(123) End Sub End Class Class base Protected WithEvents w As cls1 End Class Class cls2 Inherits base Public Sub Test() Dim o As New cls1 o.raiser() w = o o.raiser() w = o o.raiser() w = Nothing o.raiser() End Sub Public Shared Sub main() Call (New cls2).Test() End Sub Private Sub handler() Handles w.E1, w.E1 Console.WriteLine("handled") End Sub Private shared Sub handlerS() Handles w.E1, w.E1 Console.WriteLine("handledS") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled handled handledS handledS handled handled handledS handledS ]]>).VerifyIL("cls2.set_w", <![CDATA[ { // Code size 196 (0xc4) .maxstack 2 .locals init (cls1.E1EventHandler V_0, cls1.E1EventHandler V_1, cls1.E1EventHandler V_2, cls1.E1EventHandler V_3, cls1 V_4) IL_0000: ldarg.0 IL_0001: ldftn "Sub cls2._Lambda$__R0-1(Integer)" IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldarg.0 IL_000e: ldftn "Sub cls2._Lambda$__R0-2(Integer)" IL_0014: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_0019: stloc.1 IL_001a: ldsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler" IL_001f: brfalse.s IL_0028 IL_0021: ldsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler" IL_0026: br.s IL_003e IL_0028: ldsfld "cls2._Closure$__.$I As cls2._Closure$__" IL_002d: ldftn "Sub cls2._Closure$__._Lambda$__R0-3(Integer)" IL_0033: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_0038: dup IL_0039: stsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler" IL_003e: stloc.2 IL_003f: ldsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler" IL_0044: brfalse.s IL_004d IL_0046: ldsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler" IL_004b: br.s IL_0063 IL_004d: ldsfld "cls2._Closure$__.$I As cls2._Closure$__" IL_0052: ldftn "Sub cls2._Closure$__._Lambda$__R0-4(Integer)" IL_0058: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_005d: dup IL_005e: stsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler" IL_0063: stloc.3 IL_0064: ldarg.0 IL_0065: call "Function base.get_w() As cls1" IL_006a: stloc.s V_4 IL_006c: ldloc.s V_4 IL_006e: brfalse.s IL_0090 IL_0070: ldloc.s V_4 IL_0072: ldloc.0 IL_0073: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0078: ldloc.s V_4 IL_007a: ldloc.1 IL_007b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0080: ldloc.s V_4 IL_0082: ldloc.2 IL_0083: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0088: ldloc.s V_4 IL_008a: ldloc.3 IL_008b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0090: ldarg.0 IL_0091: ldarg.1 IL_0092: call "Sub base.set_w(cls1)" IL_0097: ldarg.0 IL_0098: call "Function base.get_w() As cls1" IL_009d: stloc.s V_4 IL_009f: ldloc.s V_4 IL_00a1: brfalse.s IL_00c3 IL_00a3: ldloc.s V_4 IL_00a5: ldloc.0 IL_00a6: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_00ab: ldloc.s V_4 IL_00ad: ldloc.1 IL_00ae: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_00b3: ldloc.s V_4 IL_00b5: ldloc.2 IL_00b6: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_00bb: ldloc.s V_4 IL_00bd: ldloc.3 IL_00be: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_00c3: ret } ]]>).Compilation End Sub <Fact> Public Sub PartialHandles() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class cls1 Event E1(x As Integer) Sub raiser() RaiseEvent E1(123) End Sub End Class Class base Public WithEvents w As cls1 End Class Class cls2 Inherits base Public Sub Test() Dim o As New cls1 o.raiser() w = o o.raiser() w = o o.raiser() w = Nothing o.raiser() End Sub Public Shared Sub main() Call (New cls2).Test() End Sub Private Sub handlerConcrete() Handles w.E1, w.E1 Console.WriteLine("handled") End Sub Partial Private Sub handlerConcrete() Handles w.E1, w.E1 End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled handled handled handled handled handled handled handled ]]>).VerifyIL("cls2.set_w", <![CDATA[ { // Code size 148 (0x94) .maxstack 2 .locals init (cls1.E1EventHandler V_0, cls1.E1EventHandler V_1, cls1.E1EventHandler V_2, cls1.E1EventHandler V_3, cls1 V_4) IL_0000: ldarg.0 IL_0001: ldftn "Sub cls2._Lambda$__R0-1(Integer)" IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldarg.0 IL_000e: ldftn "Sub cls2._Lambda$__R0-2(Integer)" IL_0014: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_0019: stloc.1 IL_001a: ldarg.0 IL_001b: ldftn "Sub cls2._Lambda$__R0-3(Integer)" IL_0021: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_0026: stloc.2 IL_0027: ldarg.0 IL_0028: ldftn "Sub cls2._Lambda$__R0-4(Integer)" IL_002e: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_0033: stloc.3 IL_0034: ldarg.0 IL_0035: call "Function base.get_w() As cls1" IL_003a: stloc.s V_4 IL_003c: ldloc.s V_4 IL_003e: brfalse.s IL_0060 IL_0040: ldloc.s V_4 IL_0042: ldloc.0 IL_0043: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0048: ldloc.s V_4 IL_004a: ldloc.1 IL_004b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0050: ldloc.s V_4 IL_0052: ldloc.2 IL_0053: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0058: ldloc.s V_4 IL_005a: ldloc.3 IL_005b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0060: ldarg.0 IL_0061: ldarg.1 IL_0062: call "Sub base.set_w(cls1)" IL_0067: ldarg.0 IL_0068: call "Function base.get_w() As cls1" IL_006d: stloc.s V_4 IL_006f: ldloc.s V_4 IL_0071: brfalse.s IL_0093 IL_0073: ldloc.s V_4 IL_0075: ldloc.0 IL_0076: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_007b: ldloc.s V_4 IL_007d: ldloc.1 IL_007e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_0083: ldloc.s V_4 IL_0085: ldloc.2 IL_0086: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_008b: ldloc.s V_4 IL_008d: ldloc.3 IL_008e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_0093: ret } ]]>).Compilation End Sub <Fact> Public Sub PartialHandles1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class cls1 Event E1(x As Integer) Sub raiser() RaiseEvent E1(123) End Sub End Class Class base Event E2(x As Integer) Public WithEvents w As cls1 End Class Class cls2 Inherits base Public Sub Test() Dim o As New cls1 o.raiser() w = o o.raiser() w = o o.raiser() w = Nothing o.raiser() End Sub Public Shared Sub main() Call (New cls2).Test() End Sub Partial Private Sub handlerPartial(x as integer) Handles w.E1 End Sub Partial Private Sub handlerPartial() Handles w.E1 End Sub Partial Private Sub handlerPartial1(x as integer) Handles me.E2 End Sub Partial Private Sub handlerPartial2() Handles me.E2 End Sub End Class </file> </compilation>, expectedOutput:="") End Sub <Fact> Public Sub ProtectedWithEvents() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class c1 Protected Event e() Sub raiser() RaiseEvent e() End Sub End Class Class c2 Inherits c1 End Class Class c3 Inherits c2 Sub goo() Handles MyBase.e gstrexpectedresult = "working!!" End Sub End Class Module m1 Public gstrexpectedresult As String Sub main() Dim o As New c3 o.raiser() Console.WriteLine(gstrexpectedresult) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[working!! ]]>).Compilation End Sub <Fact> Public Sub GenericWithEvents() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module m1 Public gresult As String = "" Sub main() Dim t As New C1(Of TClass) t.o = New TClass t.o.raiser() Console.WriteLine(gresult) End Sub End Module Class C1(Of T As {iTest, Class}) Public WithEvents o As T Sub EventHandler2() Handles o.Event2 gresult = gresult &amp; "inside EventHandler2" End Sub Sub EventHandler1() gresult = gresult &amp; "inside EH1" End Sub Sub adder() AddHandler o.Event2, AddressOf EventHandler1 End Sub End Class Class TClass Implements iTest Public Event Event21() Implements iTest.Event2 Sub raiser() RaiseEvent Event21() End Sub End Class Public Interface iTest Event Event2() End Interface </file> </compilation>, expectedOutput:=<![CDATA[inside EventHandler2 ]]>).VerifyIL("C1(Of T).set_o(T)", <![CDATA[ { // Code size 79 (0x4f) .maxstack 2 .locals init (iTest.Event2EventHandler V_0, T V_1) IL_0000: ldarg.0 IL_0001: ldftn "Sub C1(Of T).EventHandler2()" IL_0007: newobj "Sub iTest.Event2EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldarg.0 IL_000e: ldfld "C1(Of T)._o As T" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: box "T" IL_001a: brfalse.s IL_002a IL_001c: ldloca.s V_1 IL_001e: ldloc.0 IL_001f: constrained. "T" IL_0025: callvirt "Sub iTest.remove_Event2(iTest.Event2EventHandler)" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: stfld "C1(Of T)._o As T" IL_0031: ldarg.0 IL_0032: ldfld "C1(Of T)._o As T" IL_0037: stloc.1 IL_0038: ldloc.1 IL_0039: box "T" IL_003e: brfalse.s IL_004e IL_0040: ldloca.s V_1 IL_0042: ldloc.0 IL_0043: constrained. "T" IL_0049: callvirt "Sub iTest.add_Event2(iTest.Event2EventHandler)" IL_004e: ret } ]]>).Compilation End Sub <Fact> Public Sub GenericWithEventsNoOpt() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module m1 Public gresult As String = "" Sub main() Dim t As New C1(Of TClass) t.o = New TClass t.o.raiser() Console.WriteLine(gresult) End Sub End Module Class C1(Of T As {iTest, Class}) Public WithEvents o As T Sub EventHandler2() Handles o.Event2 gresult = gresult &amp; "inside EventHandler2" End Sub Sub EventHandler1() gresult = gresult &amp; "inside EH1" End Sub Sub adder() AddHandler o.Event2, AddressOf EventHandler1 End Sub End Class Class TClass Implements iTest Public Event Event21() Implements iTest.Event2 Sub raiser() RaiseEvent Event21() End Sub End Class Public Interface iTest Event Event2() End Interface </file> </compilation>, expectedOutput:="inside EventHandler2") c.VerifyIL("C1(Of T).set_o(T)", <![CDATA[ { // Code size 79 (0x4f) .maxstack 2 .locals init (iTest.Event2EventHandler V_0, T V_1) IL_0000: ldarg.0 IL_0001: ldftn "Sub C1(Of T).EventHandler2()" IL_0007: newobj "Sub iTest.Event2EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldarg.0 IL_000e: ldfld "C1(Of T)._o As T" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: box "T" IL_001a: brfalse.s IL_002a IL_001c: ldloca.s V_1 IL_001e: ldloc.0 IL_001f: constrained. "T" IL_0025: callvirt "Sub iTest.remove_Event2(iTest.Event2EventHandler)" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: stfld "C1(Of T)._o As T" IL_0031: ldarg.0 IL_0032: ldfld "C1(Of T)._o As T" IL_0037: stloc.1 IL_0038: ldloc.1 IL_0039: box "T" IL_003e: brfalse.s IL_004e IL_0040: ldloca.s V_1 IL_0042: ldloc.0 IL_0043: constrained. "T" IL_0049: callvirt "Sub iTest.add_Event2(iTest.Event2EventHandler)" IL_004e: ret } ]]>) End Sub <WorkItem(6214, "https://github.com/dotnet/roslyn/issues/6214")> <WorkItem(545182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545182")> <WorkItem(545184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545184")> <Fact> Public Sub TestHandlesForWithEventsFromBaseFromADifferentAssembly() Dim assembly1Compilation = CreateVisualBasicCompilation("TestHandlesForWithEventsFromBaseFromADifferentAssembly_Assembly1", <![CDATA[Public Class c1 Sub New() goo = Me End Sub Public Event loo() Public WithEvents goo As c1 Sub raise() RaiseEvent loo() End Sub End Class]]>, compilationOptions:=TestOptions.ReleaseDll) ' Verify that "AccessedThroughPropertyAttribute" is being emitted for WithEvents field. Dim assembly1Verifier = CompileAndVerify(assembly1Compilation, expectedSignatures:= { Signature("c1", "_goo", ".field [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] " & "[System.Runtime.CompilerServices.AccessedThroughPropertyAttribute(""goo"")] private instance c1 _goo") }) assembly1Verifier.VerifyDiagnostics() Dim assembly2Compilation = CreateVisualBasicCompilation("TestHandlesForWithEventsFromBaseFromADifferentAssembly_Assembly2", <![CDATA[Imports System Class c2 Inherits c1 Public res As Boolean = False Sub test() Handles goo.loo 'here res = True End Sub End Class Public Module Program Sub Main() Dim c As New c2 c.goo.raise() Console.WriteLine(c.res) End Sub End Module]]>, compilationOptions:=TestOptions.ReleaseExe, referencedCompilations:={assembly1Compilation}) CompileAndVerify(assembly2Compilation, <![CDATA[True]]>).VerifyDiagnostics() End Sub <WorkItem(6214, "https://github.com/dotnet/roslyn/issues/6214")> <WorkItem(545185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545185")> <Fact> Public Sub TestNameOfWithEventsSetterParameter() Dim comp = CreateVisualBasicCompilation("TestNameOfWithEventsSetterParameter", <![CDATA[Public Class c1 Sub New() goo = Me End Sub Public WithEvents goo As c1 End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim verifier = CompileAndVerify(comp, expectedSignatures:= { Signature("c1", "goo", ".property readwrite instance c1 goo"), Signature("c1", "set_goo", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public newslot strict specialname virtual instance System.Void set_goo(c1 WithEventsValue) cil managed synchronized"), Signature("c1", "get_goo", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public newslot strict specialname virtual instance c1 get_goo() cil managed") }) verifier.VerifyDiagnostics() End Sub <WorkItem(529548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529548")> <Fact()> Public Sub TestIssueWeFixedInNativeCompiler() Dim comp = CreateVisualBasicCompilation("TestIssueWeFixedInNativeCompiler", <![CDATA[ Imports System Interface I1(Of U) Event E1(ByVal a As U) End Interface Class C1(Of T As {Exception, I1(Of T)}) Dim WithEvents x As T 'Native compiler used to report an incorrect error on the below line - "Method 'Public Sub goo(a As T)' cannot handle event 'Public Event E1(a As U)' because they do not have a compatible signature". 'This was a bug in the native compiler (see Bug: VSWhidbey/544224) that got fixed in Roslyn. 'See Vladimir's comments in bug 13489 for more details. Sub goo(ByVal a As T) Handles x.E1 End Sub Sub bar() AddHandler x.E1, AddressOf goo 'AddHandler should also work End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim verifier = CompileAndVerify(comp) verifier.VerifyDiagnostics() End Sub <WorkItem(545188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545188")> <Fact> Public Sub Bug13470() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System Class Program Shared Sub Main() Dim c1 = GetType(C1) Dim _Goo = c1.GetField("_Goo", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance) Dim obsolete = _Goo.GetCustomAttributes(GetType(ObsoleteAttribute), False) System.Console.WriteLine(obsolete.Length = 1) End Sub End Class Class C1 <Obsolete> WithEvents Goo as C1 End Class ]]></file> </compilation>, expectedOutput:="True") End Sub <WorkItem(545187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545187")> <Fact> Public Sub Bug13469() 'Note: Below IL is for the following VB code compiled with Dev11 (using /debug-) - 'Public Class c1 ' Sub New() ' goo = Me ' End Sub ' Public Event loo() ' Public WithEvents goo As C1 ' Sub raise() ' RaiseEvent loo() ' End Sub 'End Class Dim customIL = <![CDATA[ .class public auto ansi c1 extends [mscorlib]System.Object { .class auto ansi sealed nested public looEventHandler extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method looEventHandler::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method looEventHandler::BeginInvoke .method public newslot strict virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method looEventHandler::EndInvoke .method public newslot strict virtual instance void Invoke() runtime managed { } // end of method looEventHandler::Invoke } // end of class looEventHandler .field private class c1/looEventHandler looEvent .field private class c1 _goo .custom instance void [mscorlib]System.Runtime.CompilerServices.AccessedThroughPropertyAttribute::.ctor(string) = ( 01 00 03 67 6F 6F 00 00 ) // ...goo.. .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: callvirt instance void c1::set_goo(class c1) IL_000d: ret } // end of method c1::.ctor .method public specialname instance void add_loo(class c1/looEventHandler obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class c1/looEventHandler c1::looEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass c1/looEventHandler IL_0012: stfld class c1/looEventHandler c1::looEvent IL_0017: ret } // end of method c1::add_loo .method public specialname instance void remove_loo(class c1/looEventHandler obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class c1/looEventHandler c1::looEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass c1/looEventHandler IL_0012: stfld class c1/looEventHandler c1::looEvent IL_0017: ret } // end of method c1::remove_loo .method public newslot specialname strict virtual instance class c1 get_goo() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (class c1 V_0) IL_0000: ldarg.0 IL_0001: ldfld class c1 c1::_goo IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method c1::get_goo .method public newslot specialname strict virtual instance void set_goo(class c1 WithEventsValue) cil managed synchronized { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld class c1 c1::_goo IL_0007: ret } // end of method c1::set_goo .method public instance void raise() cil managed { // Code size 17 (0x11) .maxstack 1 .locals init (class c1/looEventHandler V_0) IL_0000: ldarg.0 IL_0001: ldfld class c1/looEventHandler c1::looEvent IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0010 IL_000a: ldloc.0 IL_000b: callvirt instance void c1/looEventHandler::Invoke() IL_0010: ret } // end of method c1::raise .event c1/looEventHandler loo { .addon instance void c1::add_loo(class c1/looEventHandler) .removeon instance void c1::remove_loo(class c1/looEventHandler) } // end of event c1::loo .property instance class c1 goo() { .get instance class c1 c1::get_goo() .set instance void c1::set_goo(class c1) } // end of property c1::goo } // end of class c1 ]]> Dim compilation = CreateCompilationWithCustomILSource( <compilation> <file name="a.vb"> Imports System Class c2 Inherits c1 Public res As Boolean = False Sub test() Handles goo.loo 'here res = True End Sub End Class Public Module Program Sub Main() Dim c As New c2 c.goo.raise() Console.WriteLine(c.res) End Sub End Module </file> </compilation>, customIL.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="True").VerifyDiagnostics() End Sub <Fact> Public Sub SynthesizedOverridingWithEventsProperty() Dim source = <compilation> <file> Public Class Base Protected Friend WithEvents w As Base = Me Public Event e As System.Action Sub H1() Handles w.e End Sub End Class Public Class Derived Inherits Base Sub H2() Handles w.e End Sub End Class </file> </compilation> CompileAndVerify(source) End Sub <Fact(), WorkItem(545250, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545250")> Public Sub HookupOrder() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Public Class Base Protected Friend WithEvents w As Base = Me Public Event e As Action(Of Integer) Sub BaseH1() Handles w.e Console.WriteLine(" BaseH1") End Sub Function BaseH2(ParamArray x() As Integer) Handles Me.e Console.WriteLine(" BaseH2") Return 0 End Function Sub Raise() RaiseEvent e(1) End Sub End Class Public Class Derived Inherits Base Function DerivedH2(ParamArray x() As Integer) Handles Me.e Console.WriteLine(" DerivedH2") Return 0 End Function Sub DerivedH1() Handles w.e Console.WriteLine(" DerivedH1") End Sub End Class Public Module Program Sub Main() Console.WriteLine("Base") Dim x = New Base() x.Raise() Console.WriteLine("Derived") x = New Derived x.Raise() End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[Base BaseH2 BaseH1 Derived BaseH2 BaseH1 DerivedH1 DerivedH2 ]]>) End Sub <Fact, WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")> Public Sub TestExecutionOrder1() Dim vbCompilation = CreateVisualBasicCompilation("TestExecutionOrder1", <![CDATA[Imports System, System.Collections.Generic Public Interface I(Of T) Event e As Action(Of List(Of T)) End Interface Public Class Base(Of T, U As Class, V As Structure, W As {T, Exception}, X As {Dictionary(Of U, V), IDictionary(Of U, V)}, Y As IList(Of IList(Of T))) : Implements I(Of T) Public WithEvents Base As Base(Of T, U, V, W, X, Y) = Me Public WithEvents w3 As I(Of T) Public Event e As Action(Of List(Of T)) Implements I(Of T).e Public Sub Raise() RaiseEvent e(Nothing) End Sub Public Class Base2(Of A As {T, ArgumentException}, B As U, C As X, D As A) : Inherits Base(Of A, U, V, D, C, IList(Of IList(Of A))) Public WithEvents w As U Public Shadows WithEvents Base2 As Base(Of T, U, V, W, X, Y).Base2(Of A, B, C, D) = Me Public Shadows WithEvents Base33 As Base3 Public Shadows Event e As Action(Of HashSet(Of T), Dictionary(Of T, W)) Public Sub Raise2() RaiseEvent e(Nothing, Nothing) End Sub Public Class Base3 : Inherits Base2(Of A, B, C, D) Public Shadows WithEvents Base3 As Base(Of A, U, V, D, C, IList(Of IList(Of A))) = Me Function Goo(x As HashSet(Of A), y As Dictionary(Of A, D)) As Integer Handles Base33.e Console.WriteLine("1") Return 0 End Function Function Goo(x As List(Of A)) As Dictionary(Of T, A) Handles Base3.e Console.WriteLine("2") Return New Dictionary(Of T, A) End Function End Class End Class End Class Public Structure S End Structure Public Class Derived(Of T As {Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException)))}) : Inherits Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException))). Base2(Of ArgumentException, String, Dictionary(Of String, S), ArgumentNullException). Base3 : Implements I(Of ArgumentException) Shadows Event e As Action(Of List(Of ArgumentException)) Implements I(Of ArgumentException).e Public Shadows WithEvents w As T = New Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException))) Public WithEvents w2 As Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException))). Base2(Of ArgumentException, String, Dictionary(Of String, S), ArgumentNullException). Base3 = New Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException))). Base2(Of ArgumentException, String, Dictionary(Of String, S), ArgumentNullException). Base3 Shadows Sub Goo(x As HashSet(Of ArgumentException), y As Dictionary(Of ArgumentException, ArgumentNullException)) Handles Base2.e Console.WriteLine("3") End Sub Shadows Sub Goo() Handles Base3.e Console.WriteLine("4") End Sub Shadows Sub Goo(x As List(Of ArgumentException)) Handles w.e, Me.e, MyClass.e Console.WriteLine("5") End Sub Overloads Function goo2$(x As HashSet(Of ArgumentException), y As Dictionary(Of ArgumentException, ArgumentNullException)) Handles w2.e Console.WriteLine("6") Return 1.0 End Function Function [function](x As List(Of ArgumentException)) Handles w.e, Me.e, MyClass.e Console.WriteLine("7") Return 1.0 End Function Sub Raise3() RaiseEvent e(Nothing) End Sub End Class Public Module Program Sub Main() Dim x = New Derived(Of Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException)))) x.Raise() x.Raise2() x.w.Raise() x.w2.Raise() x.w2.Raise2() x.Raise3() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)) 'Breaking Change: Dev11 processes event handlers in a different order than Roslyn. Dim vbVerifier = CompileAndVerify(vbCompilation, expectedOutput:=<![CDATA[2 4 3 5 7 2 6 5 5 7 7]]>) vbVerifier.VerifyDiagnostics() End Sub <Fact, WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")> Public Sub TestExecutionOrder2() Dim assembly1Compilation = CreateVisualBasicCompilation("TestExecutionOrder2", <![CDATA[Option Strict Off Imports System, System.Runtime.CompilerServices Imports AliasedType = Base <Assembly: InternalsVisibleTo("Assembly2")> Public Class Base Protected WithEvents w As AliasedType = Me, x As Base = Me, y As Base = Me, z As New System.Collections.Generic.List(Of String) From {"123"} Protected Friend Event e As Action(Of Integer) Friend Sub H1() Handles w.e, x.e Console.WriteLine("Base H1") End Sub Public Function H2(ParamArray x() As Integer) Handles x.e, w.e, Me.e, MyClass.e Console.WriteLine("Base H2") Return 0 End Function Overridable Sub Raise() RaiseEvent e(1) End Sub End Class Public Class Base2 : Inherits Base End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim assembly1Verifier = CompileAndVerify(assembly1Compilation) assembly1Verifier.VerifyDiagnostics() Dim assembly2Compilation = CreateVisualBasicCompilation("Assembly2", <![CDATA[Imports System Public Class Derived : Inherits Base2 Shadows Event e As Action(Of Exception) Private Shadows Sub H1() Handles y.e, MyBase.e, x.e, w.e Console.WriteLine("Derived H1") End Sub Protected Shadows Function H2(ParamArray x() As Integer) Handles MyBase.e Console.WriteLine("Derived H2") Return 0 End Function End Class Public Module Program Sub Main() Console.WriteLine("Base") Dim x = New Base() x.Raise() Console.WriteLine("Derived") x = New Derived x.Raise() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={assembly1Compilation}) 'Breaking Change: Dev11 processes event handlers in a different order than Roslyn. Dim assembly2Verifier = CompileAndVerify(assembly2Compilation, expectedOutput:=<![CDATA[Base Base H2 Base H2 Base H1 Base H2 Base H1 Base H2 Derived Base H2 Base H2 Base H1 Base H2 Derived H1 Base H1 Base H2 Derived H1 Derived H1 Derived H1 Derived H2]]>) assembly2Verifier.VerifyDiagnostics() End Sub <Fact(), WorkItem(545250, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545250"), WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")> Public Sub TestCrossLanguageOptionalAndParamarray1() Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndParamarray1_CS", <![CDATA[public class CSClass { public delegate int bar(string x = ""); public event bar ev; public void raise() { ev("BASE"); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndParamarray1_VB", <![CDATA[Imports System Public Class VBClass : Inherits CSClass Public WithEvents w As CSClass = New CSClass Function Goo(x As String) Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED1") Return 0 End Function Function Goo(x As String, ParamArray y() As Integer) Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED2") Return 0 End Function Function Goo2(Optional x As String = "") Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED3") Return 0 End Function Function Goo2(ParamArray x() As String) Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED4") Return 0 End Function Function Goo2(x As String, Optional y As Integer = 0) Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED5") Return 0 End Function Function Goo3(Optional x As String = "", Optional y As Integer = 0) Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED6") Return 0 End Function End Class Public Module Program Sub Main() Dim x = New VBClass x.raise() x.w.raise() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) 'Breaking Change: Dev11 processes event handlers in a different order than Roslyn. Dim vbVerifier = CompileAndVerify(vbCompilation, expectedOutput:=<![CDATA[BASE DERIVED1 BASE DERIVED1 BASE DERIVED2 BASE DERIVED2 BASE DERIVED3 BASE DERIVED3 System.String[] DERIVED4 System.String[] DERIVED4 BASE DERIVED5 BASE DERIVED5 BASE DERIVED6 BASE DERIVED6 BASE DERIVED1 BASE DERIVED2 BASE DERIVED3 System.String[] DERIVED4 BASE DERIVED5 BASE DERIVED6]]>) vbVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestCrossLanguageOptionalAndPAramarray2() Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndPAramarray2_CS", <![CDATA[public class CSClass { public delegate int bar(params int[] y); public event bar ev; public void raise() { ev(1, 2, 3); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndPAramarray2_VB", <![CDATA[Imports System Public Class VBClass : Inherits CSClass Public WithEvents w As CSClass = New CSClass Function Goo(x As Integer()) Handles w.ev, MyBase.ev, Me.ev Console.WriteLine(x) Console.WriteLine("DERIVED1") Return 0 End Function Function Goo2(ParamArray x As Integer()) Handles w.ev, MyBase.ev, Me.ev Console.WriteLine(x) Console.WriteLine("DERIVED2") Return 0 End Function End Class Public Module Program Sub Main() Dim x = New VBClass x.raise() x.w.Raise() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) Dim vbVerifier = CompileAndVerify(vbCompilation, expectedOutput:=<![CDATA[System.Int32[] DERIVED1 System.Int32[] DERIVED1 System.Int32[] DERIVED2 System.Int32[] DERIVED2 System.Int32[] DERIVED1 System.Int32[] DERIVED2]]>) vbVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestCrossLanguageOptionalAndParamarray_Error1() Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndParamarray_Error1_CS", <![CDATA[public class CSClass { public delegate int bar(params int[] y); public event bar ev; public void raise() { ev(1, 2, 3); } }]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndParamarray_Error1_VB", <![CDATA[Imports System Public Class VBClass : Inherits CSClass Public WithEvents w As CSClass = New CSClass Function Goo2(x As Integer) Handles w.ev, MyBase.ev, Me.ev Console.WriteLine(x) Console.WriteLine("DERIVED1") Return 0 End Function Function Goo2(x As Integer, Optional y As Integer = 1) Handles w.ev, MyBase.ev, Me.ev Console.WriteLine(x) Console.WriteLine("DERIVED2") Return 0 End Function End Class Public Module Program Sub Main() Dim x = New VBClass x.raise() x.w.Raise() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) vbCompilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev")) End Sub <Fact, WorkItem(545257, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545257")> Public Sub TestCrossLanguageOptionalAndParamarray_Error2() Dim csCompilation = CreateCSharpCompilation("CS", <![CDATA[public class CSClass { public delegate int bar(params int[] y); public event bar ev; public void raise() { ev(1, 2, 3); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VB", <![CDATA[Imports System Public Class VBClass : Inherits CSClass Public WithEvents w As CSClass = New CSClass Function Goo(Optional x As Integer = 1) Handles w.ev, MyBase.ev, Me.ev Console.WriteLine(x) Console.WriteLine("PASS") Return 0 End Function End Class Public Module Program Sub Main() Dim x = New VBClass x.raise() x.w.Raise() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) vbCompilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev")) End Sub <Fact> Public Sub DelegateRelaxationStubsUniqueNaming1() Dim source = <compilation> <file name="a.vb"> Imports System Class WE Event V As Action(Of Integer, Integer) Event W As Action(Of Long, Long) End Class Class B Public WithEvents A3 As WE End Class Class D Inherits B Public WithEvents A1 As WE Public WithEvents A2 As WE End Class Class E Inherits D Sub G(z1 As Double, z2 As Double) Handles A1.V, A3.W Console.WriteLine(z1 + z2) End Sub Sub G(z1 As Double, z2 As Integer) Handles A1.V, A3.W Console.WriteLine(z1 + z2) End Sub Sub G(z1 As Integer, z2 As Double) Handles A2.V, A3.W, A1.V Console.WriteLine(z1 + z2) End Sub Sub G(z1 As Byte, z2 As Integer) Handles A2.V, A3.W, A1.V Console.WriteLine(z1 + z2) End Sub Sub F(z1 As Byte, z2 As Integer) Handles A2.V, A3.W, A1.V Console.WriteLine(z1 + z2) End Sub End Class </file> </compilation> CompileAndVerify(source) End Sub <Fact> Public Sub DelegateRelaxationStubsUniqueNaming2() Dim source = <compilation> <file name="a.vb"> Imports System Class WE Public Event V1 As Action(Of Integer) Public Event V2 As Action(Of Integer) End Class Class B Public WithEvents we As WE = New WE Public Event W1 As Action(Of Integer) Public Event W2 As Action(Of Integer) End Class Class C Inherits B Public Event U1 As Action(Of Integer) Public Event U2 As Action(Of Integer) Sub F() Handles we.V1, we.V2, MyBase.W1, MyBase.W2, Me.U1, Me.U2 End Sub End Class </file> </compilation> CompileAndVerify(source) End Sub <Fact, WorkItem(4544, "https://github.com/dotnet/roslyn/issues/4544")> Public Sub MultipleInitializationsWithAsNew_01() Dim source = <compilation> <file name="a.vb"> Class C1 Shared WithEvents a1, b1, c1 As New C2() WithEvents a2, b2, c2 As New C2() Shared a3, b3, c3 As New C2() Dim a4, b4, c4 As New C2() Shared Sub Main() Check(a1, b1, c1) Check(a3, b3, c3) Dim c as New C1() Check(c.a2, c.b2, c.c2) Check(c.a4, c.b4, c.c4) End Sub Private Shared Sub Check(a As Object, b As Object, c As Object) System.Console.WriteLine(a Is Nothing) System.Console.WriteLine(b Is Nothing) System.Console.WriteLine(c Is Nothing) System.Console.WriteLine(a Is b) System.Console.WriteLine(a Is c) System.Console.WriteLine(b Is c) End Sub End Class Class C2 End Class </file> </compilation> CompileAndVerify(source, expectedOutput:= <![CDATA[ False False False False False False False False False False False False False False False False False False False False False False False False ]]>) End Sub <Fact, WorkItem(4544, "https://github.com/dotnet/roslyn/issues/4544")> Public Sub MultipleInitializationsWithAsNew_02() Dim source = <compilation> <file name="a.vb"> Class C1 Shared WithEvents a, b, c As New C1() With {.P1 = 2} Shared Sub Main() System.Console.WriteLine(a.P1) System.Console.WriteLine(b.P1) System.Console.WriteLine(c.P1) System.Console.WriteLine(a Is b) System.Console.WriteLine(a Is c) System.Console.WriteLine(b Is c) End Sub Public P1 As Integer End Class </file> </compilation> CompileAndVerify(source, expectedOutput:= <![CDATA[ 2 2 2 False False False ]]>). VerifyIL("C1..cctor", <![CDATA[ { // Code size 52 (0x34) .maxstack 3 IL_0000: newobj "Sub C1..ctor()" IL_0005: dup IL_0006: ldc.i4.2 IL_0007: stfld "C1.P1 As Integer" IL_000c: call "Sub C1.set_a(C1)" IL_0011: newobj "Sub C1..ctor()" IL_0016: dup IL_0017: ldc.i4.2 IL_0018: stfld "C1.P1 As Integer" IL_001d: call "Sub C1.set_b(C1)" IL_0022: newobj "Sub C1..ctor()" IL_0027: dup IL_0028: ldc.i4.2 IL_0029: stfld "C1.P1 As Integer" IL_002e: call "Sub C1.set_c(C1)" IL_0033: ret } ]]>) 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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenWithEvents Inherits BasicTestBase <Fact> Public Sub SimpleWithEventsTest() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Imports System.Linq Module Program Dim WithEvents X As Object = "AA", y As New Object Sub Main(args As String()) Console.WriteLine(X) X() = 42 Console.WriteLine(X()) _Y = 123 Console.WriteLine(_Y) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ AA 42 123 ]]>).VerifyIL("Program.Main", <![CDATA[ { // Code size 70 (0x46) .maxstack 1 IL_0000: call "Function Program.get_X() As Object" IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000a: call "Sub System.Console.WriteLine(Object)" IL_000f: ldc.i4.s 42 IL_0011: box "Integer" IL_0016: call "Sub Program.set_X(Object)" IL_001b: call "Function Program.get_X() As Object" IL_0020: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0025: call "Sub System.Console.WriteLine(Object)" IL_002a: ldc.i4.s 123 IL_002c: box "Integer" IL_0031: stsfld "Program._y As Object" IL_0036: ldsfld "Program._y As Object" IL_003b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0040: call "Sub System.Console.WriteLine(Object)" IL_0045: ret } ]]>).Compilation End Sub <Fact> Public Sub StaticHandlesMe() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class Program Shared Event E1() Shared Sub Main(args As String()) RaiseEvent E1() End Sub Shared Sub goo() Handles MyClass.E1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled ]]>).VerifyIL("Program..cctor", <![CDATA[ { // Code size 18 (0x12) .maxstack 2 IL_0000: ldnull IL_0001: ldftn "Sub Program.goo()" IL_0007: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0011: ret } ]]>).Compilation End Sub <Fact> Public Sub StaticHandlesMeInBase() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System class Base Shared Event E1() shared sub raiser() RaiseEvent E1() end sub end class Class Program Inherits Base Shared Sub Main(args As String()) raiser End Sub Shared Sub goo() Handles MyClass.E1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled ]]>).VerifyIL("Program..cctor", <![CDATA[ { // Code size 18 (0x12) .maxstack 2 IL_0000: ldnull IL_0001: ldftn "Sub Program.goo()" IL_0007: newobj "Sub Base.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: call "Sub Base.add_E1(Base.E1EventHandler)" IL_0011: ret } ]]>).Compilation End Sub <Fact> Public Sub InstanceHandlesMe() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> imports system Class Program Event E1() Shared Sub Main(args As String()) Call (New Program).Raiser() End Sub Sub Raiser() RaiseEvent E1() End Sub Shared Sub goo() Handles MyClass.e1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled ]]>).VerifyIL("Program..ctor", <![CDATA[ { // Code size 25 (0x19) .maxstack 3 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldnull IL_0008: ldftn "Sub Program.goo()" IL_000e: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_0013: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0018: ret } ]]>).Compilation End Sub <Fact> Public Sub InstanceHandlesMeNeedCtor() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> imports system Class Program Event E1(x As Integer) Sub New() Me.New(42) End Sub Sub New(x As Integer) End Sub Sub New(x As Long) End Sub Shared Sub Main(args As String()) Call (New Program()).Raiser() End Sub Sub Raiser() RaiseEvent E1(123) End Sub Shared Sub goo() Handles MyClass.e1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled ]]>).VerifyIL("Program..ctor", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: call "Sub Program..ctor(Integer)" IL_0008: ret } ]]>).VerifyIL("Program..ctor(Integer)", <![CDATA[ { // Code size 49 (0x31) .maxstack 3 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler" IL_0013: br.s IL_002b IL_0015: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_001a: ldftn "Sub Program._Closure$__._Lambda$__R6-1(Integer)" IL_0020: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler" IL_002b: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0030: ret } ]]>).VerifyIL("Program..ctor(Long)", <![CDATA[ { // Code size 49 (0x31) .maxstack 3 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler" IL_0013: br.s IL_002b IL_0015: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_001a: ldftn "Sub Program._Closure$__._Lambda$__R7-2(Integer)" IL_0020: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler" IL_002b: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0030: ret } ]]>).Compilation End Sub <Fact> Public Sub InstanceHandlesMeMismatched() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option strict off Imports System Class base Event E2(ByRef x As Integer) Sub Raiser() RaiseEvent E2(123) End Sub End Class Class Program Inherits base Shared Event E1(x As Integer) Shared Sub Main(args As String()) Call (New Program).Raiser() End Sub Shadows Sub Raiser() RaiseEvent E1(123) MyBase.Raiser() End Sub Sub goo1() Handles MyClass.E1 Console.WriteLine("handled1") End Sub Shared Sub goo2() Handles MyClass.E2 Console.WriteLine("handled2") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled1 handled2 ]]>).VerifyIL("Program..ctor", <![CDATA[ { // Code size 66 (0x42) .maxstack 3 IL_0000: ldarg.0 IL_0001: call "Sub base..ctor()" IL_0006: ldarg.0 IL_0007: ldftn "Sub Program._Lambda$__R0-1(Integer)" IL_000d: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_0012: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0017: ldarg.0 IL_0018: ldsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler" IL_001d: brfalse.s IL_0026 IL_001f: ldsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler" IL_0024: br.s IL_003c IL_0026: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_002b: ldftn "Sub Program._Closure$__._Lambda$__R0-2(ByRef Integer)" IL_0031: newobj "Sub base.E2EventHandler..ctor(Object, System.IntPtr)" IL_0036: dup IL_0037: stsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler" IL_003c: call "Sub base.add_E2(base.E2EventHandler)" IL_0041: ret } ]]>).Compilation End Sub <Fact> Public Sub InstanceHandlesMeMismatchedStrict() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class base Event E2(ByRef x As Integer) Sub Raiser() RaiseEvent E2(123) End Sub End Class Class Program Inherits base Shared Event E1(x As Integer) Shared Sub Main(args As String()) Call (New Program).Raiser() End Sub Shadows Sub Raiser() RaiseEvent E1(123) MyBase.Raiser() End Sub Sub goo1() Handles MyClass.E1 Console.WriteLine("handled1") End Sub Shared Function goo2(arg As Long) As Integer Handles MyClass.E1 Console.WriteLine("handled2") Return 123 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[handled2 handled1 ]]>).VerifyIL("Program..ctor", <![CDATA[ { // Code size 24 (0x18) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub base..ctor()" IL_0006: ldarg.0 IL_0007: ldftn "Sub Program._Lambda$__R1-2(Integer)" IL_000d: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)" IL_0012: call "Sub Program.add_E1(Program.E1EventHandler)" IL_0017: ret } ]]>).Compilation End Sub <Fact> Public Sub SimpleSharedWithEvents() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class cls1 Event E1() Sub raiser() RaiseEvent E1() End Sub End Class Class cls2 Shared WithEvents w As cls1 Public Shared Sub Main() Dim o As New cls1 o.raiser() w = o o.raiser() w = o o.raiser() w = Nothing o.raiser() End Sub Private Shared Sub handler() Handles w.E1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled handled ]]>).VerifyIL("cls2.set_w", <![CDATA[ { // Code size 52 (0x34) .maxstack 2 .locals init (cls1.E1EventHandler V_0, cls1 V_1) IL_0000: ldnull IL_0001: ldftn "Sub cls2.handler()" IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldsfld "cls2._w As cls1" IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: brfalse.s IL_001d IL_0016: ldloc.1 IL_0017: ldloc.0 IL_0018: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_001d: ldarg.0 IL_001e: stsfld "cls2._w As cls1" IL_0023: ldsfld "cls2._w As cls1" IL_0028: stloc.1 IL_0029: ldloc.1 IL_002a: brfalse.s IL_0033 IL_002c: ldloc.1 IL_002d: ldloc.0 IL_002e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_0033: ret } ]]>).Compilation End Sub <Fact> Public Sub SimpleInstanceWithEvents() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> imports system Class cls1 Event E1() Sub raiser() RaiseEvent E1() End Sub End Class Class cls2 WithEvents w As cls1 Public Sub Test() Dim o As New cls1 o.raiser() w = o o.raiser() w = o o.raiser() w = Nothing o.raiser() End Sub Public Shared Sub main() Call (New cls2).Test() End Sub Private Sub handler() Handles w.E1 Console.WriteLine("handled") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled handled ]]>).VerifyIL("cls2.set_w", <![CDATA[ { // Code size 55 (0x37) .maxstack 2 .locals init (cls1.E1EventHandler V_0, cls1 V_1) IL_0000: ldarg.0 IL_0001: ldftn "Sub cls2.handler()" IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldarg.0 IL_000e: ldfld "cls2._w As cls1" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: brfalse.s IL_001e IL_0017: ldloc.1 IL_0018: ldloc.0 IL_0019: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_001e: ldarg.0 IL_001f: ldarg.1 IL_0020: stfld "cls2._w As cls1" IL_0025: ldarg.0 IL_0026: ldfld "cls2._w As cls1" IL_002b: stloc.1 IL_002c: ldloc.1 IL_002d: brfalse.s IL_0036 IL_002f: ldloc.1 IL_0030: ldloc.0 IL_0031: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_0036: ret } ]]>).Compilation End Sub <Fact> Public Sub BaseInstanceWithEventsMultiple() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class cls1 Event E1(x As Integer) Sub raiser() RaiseEvent E1(123) End Sub End Class Class base Protected WithEvents w As cls1 End Class Class cls2 Inherits base Public Sub Test() Dim o As New cls1 o.raiser() w = o o.raiser() w = o o.raiser() w = Nothing o.raiser() End Sub Public Shared Sub main() Call (New cls2).Test() End Sub Private Sub handler() Handles w.E1, w.E1 Console.WriteLine("handled") End Sub Private shared Sub handlerS() Handles w.E1, w.E1 Console.WriteLine("handledS") End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled handled handledS handledS handled handled handledS handledS ]]>).VerifyIL("cls2.set_w", <![CDATA[ { // Code size 196 (0xc4) .maxstack 2 .locals init (cls1.E1EventHandler V_0, cls1.E1EventHandler V_1, cls1.E1EventHandler V_2, cls1.E1EventHandler V_3, cls1 V_4) IL_0000: ldarg.0 IL_0001: ldftn "Sub cls2._Lambda$__R0-1(Integer)" IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldarg.0 IL_000e: ldftn "Sub cls2._Lambda$__R0-2(Integer)" IL_0014: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_0019: stloc.1 IL_001a: ldsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler" IL_001f: brfalse.s IL_0028 IL_0021: ldsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler" IL_0026: br.s IL_003e IL_0028: ldsfld "cls2._Closure$__.$I As cls2._Closure$__" IL_002d: ldftn "Sub cls2._Closure$__._Lambda$__R0-3(Integer)" IL_0033: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_0038: dup IL_0039: stsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler" IL_003e: stloc.2 IL_003f: ldsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler" IL_0044: brfalse.s IL_004d IL_0046: ldsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler" IL_004b: br.s IL_0063 IL_004d: ldsfld "cls2._Closure$__.$I As cls2._Closure$__" IL_0052: ldftn "Sub cls2._Closure$__._Lambda$__R0-4(Integer)" IL_0058: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_005d: dup IL_005e: stsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler" IL_0063: stloc.3 IL_0064: ldarg.0 IL_0065: call "Function base.get_w() As cls1" IL_006a: stloc.s V_4 IL_006c: ldloc.s V_4 IL_006e: brfalse.s IL_0090 IL_0070: ldloc.s V_4 IL_0072: ldloc.0 IL_0073: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0078: ldloc.s V_4 IL_007a: ldloc.1 IL_007b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0080: ldloc.s V_4 IL_0082: ldloc.2 IL_0083: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0088: ldloc.s V_4 IL_008a: ldloc.3 IL_008b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0090: ldarg.0 IL_0091: ldarg.1 IL_0092: call "Sub base.set_w(cls1)" IL_0097: ldarg.0 IL_0098: call "Function base.get_w() As cls1" IL_009d: stloc.s V_4 IL_009f: ldloc.s V_4 IL_00a1: brfalse.s IL_00c3 IL_00a3: ldloc.s V_4 IL_00a5: ldloc.0 IL_00a6: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_00ab: ldloc.s V_4 IL_00ad: ldloc.1 IL_00ae: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_00b3: ldloc.s V_4 IL_00b5: ldloc.2 IL_00b6: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_00bb: ldloc.s V_4 IL_00bd: ldloc.3 IL_00be: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_00c3: ret } ]]>).Compilation End Sub <Fact> Public Sub PartialHandles() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class cls1 Event E1(x As Integer) Sub raiser() RaiseEvent E1(123) End Sub End Class Class base Public WithEvents w As cls1 End Class Class cls2 Inherits base Public Sub Test() Dim o As New cls1 o.raiser() w = o o.raiser() w = o o.raiser() w = Nothing o.raiser() End Sub Public Shared Sub main() Call (New cls2).Test() End Sub Private Sub handlerConcrete() Handles w.E1, w.E1 Console.WriteLine("handled") End Sub Partial Private Sub handlerConcrete() Handles w.E1, w.E1 End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[handled handled handled handled handled handled handled handled ]]>).VerifyIL("cls2.set_w", <![CDATA[ { // Code size 148 (0x94) .maxstack 2 .locals init (cls1.E1EventHandler V_0, cls1.E1EventHandler V_1, cls1.E1EventHandler V_2, cls1.E1EventHandler V_3, cls1 V_4) IL_0000: ldarg.0 IL_0001: ldftn "Sub cls2._Lambda$__R0-1(Integer)" IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldarg.0 IL_000e: ldftn "Sub cls2._Lambda$__R0-2(Integer)" IL_0014: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_0019: stloc.1 IL_001a: ldarg.0 IL_001b: ldftn "Sub cls2._Lambda$__R0-3(Integer)" IL_0021: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_0026: stloc.2 IL_0027: ldarg.0 IL_0028: ldftn "Sub cls2._Lambda$__R0-4(Integer)" IL_002e: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)" IL_0033: stloc.3 IL_0034: ldarg.0 IL_0035: call "Function base.get_w() As cls1" IL_003a: stloc.s V_4 IL_003c: ldloc.s V_4 IL_003e: brfalse.s IL_0060 IL_0040: ldloc.s V_4 IL_0042: ldloc.0 IL_0043: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0048: ldloc.s V_4 IL_004a: ldloc.1 IL_004b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0050: ldloc.s V_4 IL_0052: ldloc.2 IL_0053: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0058: ldloc.s V_4 IL_005a: ldloc.3 IL_005b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)" IL_0060: ldarg.0 IL_0061: ldarg.1 IL_0062: call "Sub base.set_w(cls1)" IL_0067: ldarg.0 IL_0068: call "Function base.get_w() As cls1" IL_006d: stloc.s V_4 IL_006f: ldloc.s V_4 IL_0071: brfalse.s IL_0093 IL_0073: ldloc.s V_4 IL_0075: ldloc.0 IL_0076: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_007b: ldloc.s V_4 IL_007d: ldloc.1 IL_007e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_0083: ldloc.s V_4 IL_0085: ldloc.2 IL_0086: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_008b: ldloc.s V_4 IL_008d: ldloc.3 IL_008e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)" IL_0093: ret } ]]>).Compilation End Sub <Fact> Public Sub PartialHandles1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class cls1 Event E1(x As Integer) Sub raiser() RaiseEvent E1(123) End Sub End Class Class base Event E2(x As Integer) Public WithEvents w As cls1 End Class Class cls2 Inherits base Public Sub Test() Dim o As New cls1 o.raiser() w = o o.raiser() w = o o.raiser() w = Nothing o.raiser() End Sub Public Shared Sub main() Call (New cls2).Test() End Sub Partial Private Sub handlerPartial(x as integer) Handles w.E1 End Sub Partial Private Sub handlerPartial() Handles w.E1 End Sub Partial Private Sub handlerPartial1(x as integer) Handles me.E2 End Sub Partial Private Sub handlerPartial2() Handles me.E2 End Sub End Class </file> </compilation>, expectedOutput:="") End Sub <Fact> Public Sub ProtectedWithEvents() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class c1 Protected Event e() Sub raiser() RaiseEvent e() End Sub End Class Class c2 Inherits c1 End Class Class c3 Inherits c2 Sub goo() Handles MyBase.e gstrexpectedresult = "working!!" End Sub End Class Module m1 Public gstrexpectedresult As String Sub main() Dim o As New c3 o.raiser() Console.WriteLine(gstrexpectedresult) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[working!! ]]>).Compilation End Sub <Fact> Public Sub GenericWithEvents() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module m1 Public gresult As String = "" Sub main() Dim t As New C1(Of TClass) t.o = New TClass t.o.raiser() Console.WriteLine(gresult) End Sub End Module Class C1(Of T As {iTest, Class}) Public WithEvents o As T Sub EventHandler2() Handles o.Event2 gresult = gresult &amp; "inside EventHandler2" End Sub Sub EventHandler1() gresult = gresult &amp; "inside EH1" End Sub Sub adder() AddHandler o.Event2, AddressOf EventHandler1 End Sub End Class Class TClass Implements iTest Public Event Event21() Implements iTest.Event2 Sub raiser() RaiseEvent Event21() End Sub End Class Public Interface iTest Event Event2() End Interface </file> </compilation>, expectedOutput:=<![CDATA[inside EventHandler2 ]]>).VerifyIL("C1(Of T).set_o(T)", <![CDATA[ { // Code size 79 (0x4f) .maxstack 2 .locals init (iTest.Event2EventHandler V_0, T V_1) IL_0000: ldarg.0 IL_0001: ldftn "Sub C1(Of T).EventHandler2()" IL_0007: newobj "Sub iTest.Event2EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldarg.0 IL_000e: ldfld "C1(Of T)._o As T" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: box "T" IL_001a: brfalse.s IL_002a IL_001c: ldloca.s V_1 IL_001e: ldloc.0 IL_001f: constrained. "T" IL_0025: callvirt "Sub iTest.remove_Event2(iTest.Event2EventHandler)" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: stfld "C1(Of T)._o As T" IL_0031: ldarg.0 IL_0032: ldfld "C1(Of T)._o As T" IL_0037: stloc.1 IL_0038: ldloc.1 IL_0039: box "T" IL_003e: brfalse.s IL_004e IL_0040: ldloca.s V_1 IL_0042: ldloc.0 IL_0043: constrained. "T" IL_0049: callvirt "Sub iTest.add_Event2(iTest.Event2EventHandler)" IL_004e: ret } ]]>).Compilation End Sub <Fact> Public Sub GenericWithEventsNoOpt() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module m1 Public gresult As String = "" Sub main() Dim t As New C1(Of TClass) t.o = New TClass t.o.raiser() Console.WriteLine(gresult) End Sub End Module Class C1(Of T As {iTest, Class}) Public WithEvents o As T Sub EventHandler2() Handles o.Event2 gresult = gresult &amp; "inside EventHandler2" End Sub Sub EventHandler1() gresult = gresult &amp; "inside EH1" End Sub Sub adder() AddHandler o.Event2, AddressOf EventHandler1 End Sub End Class Class TClass Implements iTest Public Event Event21() Implements iTest.Event2 Sub raiser() RaiseEvent Event21() End Sub End Class Public Interface iTest Event Event2() End Interface </file> </compilation>, expectedOutput:="inside EventHandler2") c.VerifyIL("C1(Of T).set_o(T)", <![CDATA[ { // Code size 79 (0x4f) .maxstack 2 .locals init (iTest.Event2EventHandler V_0, T V_1) IL_0000: ldarg.0 IL_0001: ldftn "Sub C1(Of T).EventHandler2()" IL_0007: newobj "Sub iTest.Event2EventHandler..ctor(Object, System.IntPtr)" IL_000c: stloc.0 IL_000d: ldarg.0 IL_000e: ldfld "C1(Of T)._o As T" IL_0013: stloc.1 IL_0014: ldloc.1 IL_0015: box "T" IL_001a: brfalse.s IL_002a IL_001c: ldloca.s V_1 IL_001e: ldloc.0 IL_001f: constrained. "T" IL_0025: callvirt "Sub iTest.remove_Event2(iTest.Event2EventHandler)" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: stfld "C1(Of T)._o As T" IL_0031: ldarg.0 IL_0032: ldfld "C1(Of T)._o As T" IL_0037: stloc.1 IL_0038: ldloc.1 IL_0039: box "T" IL_003e: brfalse.s IL_004e IL_0040: ldloca.s V_1 IL_0042: ldloc.0 IL_0043: constrained. "T" IL_0049: callvirt "Sub iTest.add_Event2(iTest.Event2EventHandler)" IL_004e: ret } ]]>) End Sub <WorkItem(6214, "https://github.com/dotnet/roslyn/issues/6214")> <WorkItem(545182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545182")> <WorkItem(545184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545184")> <Fact> Public Sub TestHandlesForWithEventsFromBaseFromADifferentAssembly() Dim assembly1Compilation = CreateVisualBasicCompilation("TestHandlesForWithEventsFromBaseFromADifferentAssembly_Assembly1", <![CDATA[Public Class c1 Sub New() goo = Me End Sub Public Event loo() Public WithEvents goo As c1 Sub raise() RaiseEvent loo() End Sub End Class]]>, compilationOptions:=TestOptions.ReleaseDll) ' Verify that "AccessedThroughPropertyAttribute" is being emitted for WithEvents field. Dim assembly1Verifier = CompileAndVerify(assembly1Compilation, expectedSignatures:= { Signature("c1", "_goo", ".field [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] " & "[System.Runtime.CompilerServices.AccessedThroughPropertyAttribute(""goo"")] private instance c1 _goo") }) assembly1Verifier.VerifyDiagnostics() Dim assembly2Compilation = CreateVisualBasicCompilation("TestHandlesForWithEventsFromBaseFromADifferentAssembly_Assembly2", <![CDATA[Imports System Class c2 Inherits c1 Public res As Boolean = False Sub test() Handles goo.loo 'here res = True End Sub End Class Public Module Program Sub Main() Dim c As New c2 c.goo.raise() Console.WriteLine(c.res) End Sub End Module]]>, compilationOptions:=TestOptions.ReleaseExe, referencedCompilations:={assembly1Compilation}) CompileAndVerify(assembly2Compilation, <![CDATA[True]]>).VerifyDiagnostics() End Sub <WorkItem(6214, "https://github.com/dotnet/roslyn/issues/6214")> <WorkItem(545185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545185")> <Fact> Public Sub TestNameOfWithEventsSetterParameter() Dim comp = CreateVisualBasicCompilation("TestNameOfWithEventsSetterParameter", <![CDATA[Public Class c1 Sub New() goo = Me End Sub Public WithEvents goo As c1 End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim verifier = CompileAndVerify(comp, expectedSignatures:= { Signature("c1", "goo", ".property readwrite instance c1 goo"), Signature("c1", "set_goo", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public newslot strict specialname virtual instance System.Void set_goo(c1 WithEventsValue) cil managed synchronized"), Signature("c1", "get_goo", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public newslot strict specialname virtual instance c1 get_goo() cil managed") }) verifier.VerifyDiagnostics() End Sub <WorkItem(529548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529548")> <Fact()> Public Sub TestIssueWeFixedInNativeCompiler() Dim comp = CreateVisualBasicCompilation("TestIssueWeFixedInNativeCompiler", <![CDATA[ Imports System Interface I1(Of U) Event E1(ByVal a As U) End Interface Class C1(Of T As {Exception, I1(Of T)}) Dim WithEvents x As T 'Native compiler used to report an incorrect error on the below line - "Method 'Public Sub goo(a As T)' cannot handle event 'Public Event E1(a As U)' because they do not have a compatible signature". 'This was a bug in the native compiler (see Bug: VSWhidbey/544224) that got fixed in Roslyn. 'See Vladimir's comments in bug 13489 for more details. Sub goo(ByVal a As T) Handles x.E1 End Sub Sub bar() AddHandler x.E1, AddressOf goo 'AddHandler should also work End Sub End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim verifier = CompileAndVerify(comp) verifier.VerifyDiagnostics() End Sub <WorkItem(545188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545188")> <Fact> Public Sub Bug13470() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"><![CDATA[ Imports System Class Program Shared Sub Main() Dim c1 = GetType(C1) Dim _Goo = c1.GetField("_Goo", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance) Dim obsolete = _Goo.GetCustomAttributes(GetType(ObsoleteAttribute), False) System.Console.WriteLine(obsolete.Length = 1) End Sub End Class Class C1 <Obsolete> WithEvents Goo as C1 End Class ]]></file> </compilation>, expectedOutput:="True") End Sub <WorkItem(545187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545187")> <Fact> Public Sub Bug13469() 'Note: Below IL is for the following VB code compiled with Dev11 (using /debug-) - 'Public Class c1 ' Sub New() ' goo = Me ' End Sub ' Public Event loo() ' Public WithEvents goo As C1 ' Sub raise() ' RaiseEvent loo() ' End Sub 'End Class Dim customIL = <![CDATA[ .class public auto ansi c1 extends [mscorlib]System.Object { .class auto ansi sealed nested public looEventHandler extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object TargetObject, native int TargetMethod) runtime managed { } // end of method looEventHandler::.ctor .method public newslot strict virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback DelegateCallback, object DelegateAsyncState) runtime managed { } // end of method looEventHandler::BeginInvoke .method public newslot strict virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed { } // end of method looEventHandler::EndInvoke .method public newslot strict virtual instance void Invoke() runtime managed { } // end of method looEventHandler::Invoke } // end of class looEventHandler .field private class c1/looEventHandler looEvent .field private class c1 _goo .custom instance void [mscorlib]System.Runtime.CompilerServices.AccessedThroughPropertyAttribute::.ctor(string) = ( 01 00 03 67 6F 6F 00 00 ) // ...goo.. .method public specialname rtspecialname instance void .ctor() cil managed { // Code size 14 (0xe) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: callvirt instance void c1::set_goo(class c1) IL_000d: ret } // end of method c1::.ctor .method public specialname instance void add_loo(class c1/looEventHandler obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class c1/looEventHandler c1::looEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass c1/looEventHandler IL_0012: stfld class c1/looEventHandler c1::looEvent IL_0017: ret } // end of method c1::add_loo .method public specialname instance void remove_loo(class c1/looEventHandler obj) cil managed synchronized { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld class c1/looEventHandler c1::looEvent IL_0007: ldarg.1 IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) IL_000d: castclass c1/looEventHandler IL_0012: stfld class c1/looEventHandler c1::looEvent IL_0017: ret } // end of method c1::remove_loo .method public newslot specialname strict virtual instance class c1 get_goo() cil managed { // Code size 11 (0xb) .maxstack 1 .locals init (class c1 V_0) IL_0000: ldarg.0 IL_0001: ldfld class c1 c1::_goo IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method c1::get_goo .method public newslot specialname strict virtual instance void set_goo(class c1 WithEventsValue) cil managed synchronized { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld class c1 c1::_goo IL_0007: ret } // end of method c1::set_goo .method public instance void raise() cil managed { // Code size 17 (0x11) .maxstack 1 .locals init (class c1/looEventHandler V_0) IL_0000: ldarg.0 IL_0001: ldfld class c1/looEventHandler c1::looEvent IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0010 IL_000a: ldloc.0 IL_000b: callvirt instance void c1/looEventHandler::Invoke() IL_0010: ret } // end of method c1::raise .event c1/looEventHandler loo { .addon instance void c1::add_loo(class c1/looEventHandler) .removeon instance void c1::remove_loo(class c1/looEventHandler) } // end of event c1::loo .property instance class c1 goo() { .get instance class c1 c1::get_goo() .set instance void c1::set_goo(class c1) } // end of property c1::goo } // end of class c1 ]]> Dim compilation = CreateCompilationWithCustomILSource( <compilation> <file name="a.vb"> Imports System Class c2 Inherits c1 Public res As Boolean = False Sub test() Handles goo.loo 'here res = True End Sub End Class Public Module Program Sub Main() Dim c As New c2 c.goo.raise() Console.WriteLine(c.res) End Sub End Module </file> </compilation>, customIL.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:="True").VerifyDiagnostics() End Sub <Fact> Public Sub SynthesizedOverridingWithEventsProperty() Dim source = <compilation> <file> Public Class Base Protected Friend WithEvents w As Base = Me Public Event e As System.Action Sub H1() Handles w.e End Sub End Class Public Class Derived Inherits Base Sub H2() Handles w.e End Sub End Class </file> </compilation> CompileAndVerify(source) End Sub <Fact(), WorkItem(545250, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545250")> Public Sub HookupOrder() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Public Class Base Protected Friend WithEvents w As Base = Me Public Event e As Action(Of Integer) Sub BaseH1() Handles w.e Console.WriteLine(" BaseH1") End Sub Function BaseH2(ParamArray x() As Integer) Handles Me.e Console.WriteLine(" BaseH2") Return 0 End Function Sub Raise() RaiseEvent e(1) End Sub End Class Public Class Derived Inherits Base Function DerivedH2(ParamArray x() As Integer) Handles Me.e Console.WriteLine(" DerivedH2") Return 0 End Function Sub DerivedH1() Handles w.e Console.WriteLine(" DerivedH1") End Sub End Class Public Module Program Sub Main() Console.WriteLine("Base") Dim x = New Base() x.Raise() Console.WriteLine("Derived") x = New Derived x.Raise() End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[Base BaseH2 BaseH1 Derived BaseH2 BaseH1 DerivedH1 DerivedH2 ]]>) End Sub <Fact, WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")> Public Sub TestExecutionOrder1() Dim vbCompilation = CreateVisualBasicCompilation("TestExecutionOrder1", <![CDATA[Imports System, System.Collections.Generic Public Interface I(Of T) Event e As Action(Of List(Of T)) End Interface Public Class Base(Of T, U As Class, V As Structure, W As {T, Exception}, X As {Dictionary(Of U, V), IDictionary(Of U, V)}, Y As IList(Of IList(Of T))) : Implements I(Of T) Public WithEvents Base As Base(Of T, U, V, W, X, Y) = Me Public WithEvents w3 As I(Of T) Public Event e As Action(Of List(Of T)) Implements I(Of T).e Public Sub Raise() RaiseEvent e(Nothing) End Sub Public Class Base2(Of A As {T, ArgumentException}, B As U, C As X, D As A) : Inherits Base(Of A, U, V, D, C, IList(Of IList(Of A))) Public WithEvents w As U Public Shadows WithEvents Base2 As Base(Of T, U, V, W, X, Y).Base2(Of A, B, C, D) = Me Public Shadows WithEvents Base33 As Base3 Public Shadows Event e As Action(Of HashSet(Of T), Dictionary(Of T, W)) Public Sub Raise2() RaiseEvent e(Nothing, Nothing) End Sub Public Class Base3 : Inherits Base2(Of A, B, C, D) Public Shadows WithEvents Base3 As Base(Of A, U, V, D, C, IList(Of IList(Of A))) = Me Function Goo(x As HashSet(Of A), y As Dictionary(Of A, D)) As Integer Handles Base33.e Console.WriteLine("1") Return 0 End Function Function Goo(x As List(Of A)) As Dictionary(Of T, A) Handles Base3.e Console.WriteLine("2") Return New Dictionary(Of T, A) End Function End Class End Class End Class Public Structure S End Structure Public Class Derived(Of T As {Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException)))}) : Inherits Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException))). Base2(Of ArgumentException, String, Dictionary(Of String, S), ArgumentNullException). Base3 : Implements I(Of ArgumentException) Shadows Event e As Action(Of List(Of ArgumentException)) Implements I(Of ArgumentException).e Public Shadows WithEvents w As T = New Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException))) Public WithEvents w2 As Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException))). Base2(Of ArgumentException, String, Dictionary(Of String, S), ArgumentNullException). Base3 = New Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException))). Base2(Of ArgumentException, String, Dictionary(Of String, S), ArgumentNullException). Base3 Shadows Sub Goo(x As HashSet(Of ArgumentException), y As Dictionary(Of ArgumentException, ArgumentNullException)) Handles Base2.e Console.WriteLine("3") End Sub Shadows Sub Goo() Handles Base3.e Console.WriteLine("4") End Sub Shadows Sub Goo(x As List(Of ArgumentException)) Handles w.e, Me.e, MyClass.e Console.WriteLine("5") End Sub Overloads Function goo2$(x As HashSet(Of ArgumentException), y As Dictionary(Of ArgumentException, ArgumentNullException)) Handles w2.e Console.WriteLine("6") Return 1.0 End Function Function [function](x As List(Of ArgumentException)) Handles w.e, Me.e, MyClass.e Console.WriteLine("7") Return 1.0 End Function Sub Raise3() RaiseEvent e(Nothing) End Sub End Class Public Module Program Sub Main() Dim x = New Derived(Of Base(Of ArgumentException, String, S, ArgumentException, Dictionary(Of String, S), List(Of IList(Of ArgumentException)))) x.Raise() x.Raise2() x.w.Raise() x.w2.Raise() x.w2.Raise2() x.Raise3() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)) 'Breaking Change: Dev11 processes event handlers in a different order than Roslyn. Dim vbVerifier = CompileAndVerify(vbCompilation, expectedOutput:=<![CDATA[2 4 3 5 7 2 6 5 5 7 7]]>) vbVerifier.VerifyDiagnostics() End Sub <Fact, WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")> Public Sub TestExecutionOrder2() Dim assembly1Compilation = CreateVisualBasicCompilation("TestExecutionOrder2", <![CDATA[Option Strict Off Imports System, System.Runtime.CompilerServices Imports AliasedType = Base <Assembly: InternalsVisibleTo("Assembly2")> Public Class Base Protected WithEvents w As AliasedType = Me, x As Base = Me, y As Base = Me, z As New System.Collections.Generic.List(Of String) From {"123"} Protected Friend Event e As Action(Of Integer) Friend Sub H1() Handles w.e, x.e Console.WriteLine("Base H1") End Sub Public Function H2(ParamArray x() As Integer) Handles x.e, w.e, Me.e, MyClass.e Console.WriteLine("Base H2") Return 0 End Function Overridable Sub Raise() RaiseEvent e(1) End Sub End Class Public Class Base2 : Inherits Base End Class]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) Dim assembly1Verifier = CompileAndVerify(assembly1Compilation) assembly1Verifier.VerifyDiagnostics() Dim assembly2Compilation = CreateVisualBasicCompilation("Assembly2", <![CDATA[Imports System Public Class Derived : Inherits Base2 Shadows Event e As Action(Of Exception) Private Shadows Sub H1() Handles y.e, MyBase.e, x.e, w.e Console.WriteLine("Derived H1") End Sub Protected Shadows Function H2(ParamArray x() As Integer) Handles MyBase.e Console.WriteLine("Derived H2") Return 0 End Function End Class Public Module Program Sub Main() Console.WriteLine("Base") Dim x = New Base() x.Raise() Console.WriteLine("Derived") x = New Derived x.Raise() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={assembly1Compilation}) 'Breaking Change: Dev11 processes event handlers in a different order than Roslyn. Dim assembly2Verifier = CompileAndVerify(assembly2Compilation, expectedOutput:=<![CDATA[Base Base H2 Base H2 Base H1 Base H2 Base H1 Base H2 Derived Base H2 Base H2 Base H1 Base H2 Derived H1 Base H1 Base H2 Derived H1 Derived H1 Derived H1 Derived H2]]>) assembly2Verifier.VerifyDiagnostics() End Sub <Fact(), WorkItem(545250, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545250"), WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")> Public Sub TestCrossLanguageOptionalAndParamarray1() Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndParamarray1_CS", <![CDATA[public class CSClass { public delegate int bar(string x = ""); public event bar ev; public void raise() { ev("BASE"); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndParamarray1_VB", <![CDATA[Imports System Public Class VBClass : Inherits CSClass Public WithEvents w As CSClass = New CSClass Function Goo(x As String) Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED1") Return 0 End Function Function Goo(x As String, ParamArray y() As Integer) Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED2") Return 0 End Function Function Goo2(Optional x As String = "") Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED3") Return 0 End Function Function Goo2(ParamArray x() As String) Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED4") Return 0 End Function Function Goo2(x As String, Optional y As Integer = 0) Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED5") Return 0 End Function Function Goo3(Optional x As String = "", Optional y As Integer = 0) Handles w.ev, MyBase.ev, MyClass.ev Console.WriteLine(x) Console.WriteLine("DERIVED6") Return 0 End Function End Class Public Module Program Sub Main() Dim x = New VBClass x.raise() x.w.raise() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) 'Breaking Change: Dev11 processes event handlers in a different order than Roslyn. Dim vbVerifier = CompileAndVerify(vbCompilation, expectedOutput:=<![CDATA[BASE DERIVED1 BASE DERIVED1 BASE DERIVED2 BASE DERIVED2 BASE DERIVED3 BASE DERIVED3 System.String[] DERIVED4 System.String[] DERIVED4 BASE DERIVED5 BASE DERIVED5 BASE DERIVED6 BASE DERIVED6 BASE DERIVED1 BASE DERIVED2 BASE DERIVED3 System.String[] DERIVED4 BASE DERIVED5 BASE DERIVED6]]>) vbVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestCrossLanguageOptionalAndPAramarray2() Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndPAramarray2_CS", <![CDATA[public class CSClass { public delegate int bar(params int[] y); public event bar ev; public void raise() { ev(1, 2, 3); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndPAramarray2_VB", <![CDATA[Imports System Public Class VBClass : Inherits CSClass Public WithEvents w As CSClass = New CSClass Function Goo(x As Integer()) Handles w.ev, MyBase.ev, Me.ev Console.WriteLine(x) Console.WriteLine("DERIVED1") Return 0 End Function Function Goo2(ParamArray x As Integer()) Handles w.ev, MyBase.ev, Me.ev Console.WriteLine(x) Console.WriteLine("DERIVED2") Return 0 End Function End Class Public Module Program Sub Main() Dim x = New VBClass x.raise() x.w.Raise() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) Dim vbVerifier = CompileAndVerify(vbCompilation, expectedOutput:=<![CDATA[System.Int32[] DERIVED1 System.Int32[] DERIVED1 System.Int32[] DERIVED2 System.Int32[] DERIVED2 System.Int32[] DERIVED1 System.Int32[] DERIVED2]]>) vbVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TestCrossLanguageOptionalAndParamarray_Error1() Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndParamarray_Error1_CS", <![CDATA[public class CSClass { public delegate int bar(params int[] y); public event bar ev; public void raise() { ev(1, 2, 3); } }]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndParamarray_Error1_VB", <![CDATA[Imports System Public Class VBClass : Inherits CSClass Public WithEvents w As CSClass = New CSClass Function Goo2(x As Integer) Handles w.ev, MyBase.ev, Me.ev Console.WriteLine(x) Console.WriteLine("DERIVED1") Return 0 End Function Function Goo2(x As Integer, Optional y As Integer = 1) Handles w.ev, MyBase.ev, Me.ev Console.WriteLine(x) Console.WriteLine("DERIVED2") Return 0 End Function End Class Public Module Program Sub Main() Dim x = New VBClass x.raise() x.w.Raise() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) vbCompilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev")) End Sub <Fact, WorkItem(545257, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545257")> Public Sub TestCrossLanguageOptionalAndParamarray_Error2() Dim csCompilation = CreateCSharpCompilation("CS", <![CDATA[public class CSClass { public delegate int bar(params int[] y); public event bar ev; public void raise() { ev(1, 2, 3); } }]]>, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VB", <![CDATA[Imports System Public Class VBClass : Inherits CSClass Public WithEvents w As CSClass = New CSClass Function Goo(Optional x As Integer = 1) Handles w.ev, MyBase.ev, Me.ev Console.WriteLine(x) Console.WriteLine("PASS") Return 0 End Function End Class Public Module Program Sub Main() Dim x = New VBClass x.raise() x.w.Raise() End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) vbCompilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev"), Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev")) End Sub <Fact> Public Sub DelegateRelaxationStubsUniqueNaming1() Dim source = <compilation> <file name="a.vb"> Imports System Class WE Event V As Action(Of Integer, Integer) Event W As Action(Of Long, Long) End Class Class B Public WithEvents A3 As WE End Class Class D Inherits B Public WithEvents A1 As WE Public WithEvents A2 As WE End Class Class E Inherits D Sub G(z1 As Double, z2 As Double) Handles A1.V, A3.W Console.WriteLine(z1 + z2) End Sub Sub G(z1 As Double, z2 As Integer) Handles A1.V, A3.W Console.WriteLine(z1 + z2) End Sub Sub G(z1 As Integer, z2 As Double) Handles A2.V, A3.W, A1.V Console.WriteLine(z1 + z2) End Sub Sub G(z1 As Byte, z2 As Integer) Handles A2.V, A3.W, A1.V Console.WriteLine(z1 + z2) End Sub Sub F(z1 As Byte, z2 As Integer) Handles A2.V, A3.W, A1.V Console.WriteLine(z1 + z2) End Sub End Class </file> </compilation> CompileAndVerify(source) End Sub <Fact> Public Sub DelegateRelaxationStubsUniqueNaming2() Dim source = <compilation> <file name="a.vb"> Imports System Class WE Public Event V1 As Action(Of Integer) Public Event V2 As Action(Of Integer) End Class Class B Public WithEvents we As WE = New WE Public Event W1 As Action(Of Integer) Public Event W2 As Action(Of Integer) End Class Class C Inherits B Public Event U1 As Action(Of Integer) Public Event U2 As Action(Of Integer) Sub F() Handles we.V1, we.V2, MyBase.W1, MyBase.W2, Me.U1, Me.U2 End Sub End Class </file> </compilation> CompileAndVerify(source) End Sub <Fact, WorkItem(4544, "https://github.com/dotnet/roslyn/issues/4544")> Public Sub MultipleInitializationsWithAsNew_01() Dim source = <compilation> <file name="a.vb"> Class C1 Shared WithEvents a1, b1, c1 As New C2() WithEvents a2, b2, c2 As New C2() Shared a3, b3, c3 As New C2() Dim a4, b4, c4 As New C2() Shared Sub Main() Check(a1, b1, c1) Check(a3, b3, c3) Dim c as New C1() Check(c.a2, c.b2, c.c2) Check(c.a4, c.b4, c.c4) End Sub Private Shared Sub Check(a As Object, b As Object, c As Object) System.Console.WriteLine(a Is Nothing) System.Console.WriteLine(b Is Nothing) System.Console.WriteLine(c Is Nothing) System.Console.WriteLine(a Is b) System.Console.WriteLine(a Is c) System.Console.WriteLine(b Is c) End Sub End Class Class C2 End Class </file> </compilation> CompileAndVerify(source, expectedOutput:= <![CDATA[ False False False False False False False False False False False False False False False False False False False False False False False False ]]>) End Sub <Fact, WorkItem(4544, "https://github.com/dotnet/roslyn/issues/4544")> Public Sub MultipleInitializationsWithAsNew_02() Dim source = <compilation> <file name="a.vb"> Class C1 Shared WithEvents a, b, c As New C1() With {.P1 = 2} Shared Sub Main() System.Console.WriteLine(a.P1) System.Console.WriteLine(b.P1) System.Console.WriteLine(c.P1) System.Console.WriteLine(a Is b) System.Console.WriteLine(a Is c) System.Console.WriteLine(b Is c) End Sub Public P1 As Integer End Class </file> </compilation> CompileAndVerify(source, expectedOutput:= <![CDATA[ 2 2 2 False False False ]]>). VerifyIL("C1..cctor", <![CDATA[ { // Code size 52 (0x34) .maxstack 3 IL_0000: newobj "Sub C1..ctor()" IL_0005: dup IL_0006: ldc.i4.2 IL_0007: stfld "C1.P1 As Integer" IL_000c: call "Sub C1.set_a(C1)" IL_0011: newobj "Sub C1..ctor()" IL_0016: dup IL_0017: ldc.i4.2 IL_0018: stfld "C1.P1 As Integer" IL_001d: call "Sub C1.set_b(C1)" IL_0022: newobj "Sub C1..ctor()" IL_0027: dup IL_0028: ldc.i4.2 IL_0029: stfld "C1.P1 As Integer" IL_002e: call "Sub C1.set_c(C1)" IL_0033: ret } ]]>) End Sub End Class End Namespace
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractLanguageService`2.IVsLanguageBlock.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.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; using IVsLanguageBlock = Microsoft.VisualStudio.TextManager.Interop.IVsLanguageBlock; using IVsTextLines = Microsoft.VisualStudio.TextManager.Interop.IVsTextLines; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService<TPackage, TLanguageService> : IVsLanguageBlock { public int GetCurrentBlock( IVsTextLines pTextLines, int iCurrentLine, int iCurrentChar, VsTextSpan[] ptsBlockSpan, out string pbstrDescription, out int pfBlockAvailable) { var snapshot = this.EditorAdaptersFactoryService.GetDataBuffer(pTextLines).CurrentSnapshot; var position = snapshot?.TryGetPosition(iCurrentLine, iCurrentChar); if (position == null) { pbstrDescription = null; pfBlockAvailable = 0; return VSConstants.S_OK; } (string description, TextSpan span)? foundBlock = null; var uiThreadOperationExecutor = this.Package.ComponentModel.GetService<IUIThreadOperationExecutor>(); uiThreadOperationExecutor.Execute( ServicesVSResources.Current_block, ServicesVSResources.Determining_current_block, allowCancellation: true, showProgress: false, action: context => { foundBlock = VsLanguageBlock.GetCurrentBlock(snapshot, position.Value, context.UserCancellationToken); }); pfBlockAvailable = foundBlock != null ? 1 : 0; pbstrDescription = foundBlock?.description; if (foundBlock != null && ptsBlockSpan != null && ptsBlockSpan.Length >= 1) { ptsBlockSpan[0] = foundBlock.Value.span.ToSnapshotSpan(snapshot).ToVsTextSpan(); } return VSConstants.S_OK; } } internal static class VsLanguageBlock { public static (string description, TextSpan span)? GetCurrentBlock( ITextSnapshot snapshot, int position, CancellationToken cancellationToken) { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null || !document.SupportsSyntaxTree) { return null; } var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken); var node = syntaxFactsService.GetContainingMemberDeclaration(syntaxRoot, position, useFullSpan: false); if (node == null) { return null; } var description = syntaxFactsService.GetDisplayName(node, DisplayNameOptions.IncludeMemberKeyword | DisplayNameOptions.IncludeParameters | DisplayNameOptions.IncludeType | DisplayNameOptions.IncludeTypeParameters); return (description, node.Span); } } }
// Licensed to the .NET Foundation under one or more 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.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; using IVsLanguageBlock = Microsoft.VisualStudio.TextManager.Interop.IVsLanguageBlock; using IVsTextLines = Microsoft.VisualStudio.TextManager.Interop.IVsTextLines; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService<TPackage, TLanguageService> : IVsLanguageBlock { public int GetCurrentBlock( IVsTextLines pTextLines, int iCurrentLine, int iCurrentChar, VsTextSpan[] ptsBlockSpan, out string pbstrDescription, out int pfBlockAvailable) { var snapshot = this.EditorAdaptersFactoryService.GetDataBuffer(pTextLines).CurrentSnapshot; var position = snapshot?.TryGetPosition(iCurrentLine, iCurrentChar); if (position == null) { pbstrDescription = null; pfBlockAvailable = 0; return VSConstants.S_OK; } (string description, TextSpan span)? foundBlock = null; var uiThreadOperationExecutor = this.Package.ComponentModel.GetService<IUIThreadOperationExecutor>(); uiThreadOperationExecutor.Execute( ServicesVSResources.Current_block, ServicesVSResources.Determining_current_block, allowCancellation: true, showProgress: false, action: context => { foundBlock = VsLanguageBlock.GetCurrentBlock(snapshot, position.Value, context.UserCancellationToken); }); pfBlockAvailable = foundBlock != null ? 1 : 0; pbstrDescription = foundBlock?.description; if (foundBlock != null && ptsBlockSpan != null && ptsBlockSpan.Length >= 1) { ptsBlockSpan[0] = foundBlock.Value.span.ToSnapshotSpan(snapshot).ToVsTextSpan(); } return VSConstants.S_OK; } } internal static class VsLanguageBlock { public static (string description, TextSpan span)? GetCurrentBlock( ITextSnapshot snapshot, int position, CancellationToken cancellationToken) { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null || !document.SupportsSyntaxTree) { return null; } var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var syntaxRoot = document.GetSyntaxRootSynchronously(cancellationToken); var node = syntaxFactsService.GetContainingMemberDeclaration(syntaxRoot, position, useFullSpan: false); if (node == null) { return null; } var description = syntaxFactsService.GetDisplayName(node, DisplayNameOptions.IncludeMemberKeyword | DisplayNameOptions.IncludeParameters | DisplayNameOptions.IncludeType | DisplayNameOptions.IncludeTypeParameters); return (description, node.Span); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ThrowKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ThrowKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ThrowKeywordRecommender() : base(SyntaxKind.ThrowKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsStatementContext || context.IsGlobalStatementContext) { return true; } // void M() => throw if (context.TargetToken.Kind() == SyntaxKind.EqualsGreaterThanToken) { return true; } // val ?? throw if (context.TargetToken.Kind() == SyntaxKind.QuestionQuestionToken) { return true; } // expr ? throw : ... // expr ? ... : throw if (context.TargetToken.Kind() == SyntaxKind.QuestionToken || context.TargetToken.Kind() == SyntaxKind.ColonToken) { return context.TargetToken.Parent.Kind() == SyntaxKind.ConditionalExpression; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ThrowKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ThrowKeywordRecommender() : base(SyntaxKind.ThrowKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsStatementContext || context.IsGlobalStatementContext) { return true; } // void M() => throw if (context.TargetToken.Kind() == SyntaxKind.EqualsGreaterThanToken) { return true; } // val ?? throw if (context.TargetToken.Kind() == SyntaxKind.QuestionQuestionToken) { return true; } // expr ? throw : ... // expr ? ... : throw if (context.TargetToken.Kind() == SyntaxKind.QuestionToken || context.TargetToken.Kind() == SyntaxKind.ColonToken) { return context.TargetToken.Parent.Kind() == SyntaxKind.ConditionalExpression; } return false; } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/VisualStudio/Core/Def/Implementation/Progression/IconHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Progression; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class IconHelper { private static string GetIconName(string groupName, string itemName) => string.Format("Microsoft.VisualStudio.{0}.{1}", groupName, itemName); public static string GetIconName(string groupName, Accessibility symbolAccessibility) { switch (symbolAccessibility) { case Accessibility.Private: return GetIconName(groupName, "Private"); case Accessibility.Protected: case Accessibility.ProtectedAndInternal: case Accessibility.ProtectedOrInternal: return GetIconName(groupName, "Protected"); case Accessibility.Internal: return GetIconName(groupName, "Internal"); case Accessibility.Public: case Accessibility.NotApplicable: return GetIconName(groupName, "Public"); default: throw new ArgumentException(); } } public static void Initialize(IGlyphService glyphService, IIconService iconService) { var supportedGlyphGroups = new Dictionary<StandardGlyphGroup, string> { { StandardGlyphGroup.GlyphGroupError, "Error" }, { StandardGlyphGroup.GlyphGroupDelegate, "Delegate" }, { StandardGlyphGroup.GlyphGroupEnum, "Enum" }, { StandardGlyphGroup.GlyphGroupStruct, "Struct" }, { StandardGlyphGroup.GlyphGroupClass, "Class" }, { StandardGlyphGroup.GlyphGroupInterface, "Interface" }, { StandardGlyphGroup.GlyphGroupModule, "Module" }, { StandardGlyphGroup.GlyphGroupConstant, "Constant" }, { StandardGlyphGroup.GlyphGroupEnumMember, "EnumMember" }, { StandardGlyphGroup.GlyphGroupEvent, "Event" }, { StandardGlyphGroup.GlyphExtensionMethodPrivate, "ExtensionMethodPrivate" }, { StandardGlyphGroup.GlyphExtensionMethodProtected, "ExtensionMethodProtected" }, { StandardGlyphGroup.GlyphExtensionMethodInternal, "ExtensionMethodInternal" }, { StandardGlyphGroup.GlyphExtensionMethod, "ExtensionMethod" }, { StandardGlyphGroup.GlyphGroupMethod, "Method" }, { StandardGlyphGroup.GlyphGroupProperty, "Property" }, { StandardGlyphGroup.GlyphGroupField, "Field" }, { StandardGlyphGroup.GlyphGroupOperator, "Operator" }, { StandardGlyphGroup.GlyphReference, "Reference" } }; var supportedGlyphItems = new Dictionary<StandardGlyphItem, string> { { StandardGlyphItem.GlyphItemPrivate, "Private" }, { StandardGlyphItem.GlyphItemProtected, "Protected" }, { StandardGlyphItem.GlyphItemInternal, "Internal" }, { StandardGlyphItem.GlyphItemPublic, "Public" }, { StandardGlyphItem.GlyphItemFriend, "Friend" } }; foreach (var groupKvp in supportedGlyphGroups) { foreach (var itemKvp in supportedGlyphItems) { var iconName = GetIconName(groupKvp.Value, itemKvp.Value); var localGroup = groupKvp.Key; var localItem = itemKvp.Key; iconService.AddIcon(iconName, iconName, () => glyphService.GetGlyph(localGroup, localItem)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Progression; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class IconHelper { private static string GetIconName(string groupName, string itemName) => string.Format("Microsoft.VisualStudio.{0}.{1}", groupName, itemName); public static string GetIconName(string groupName, Accessibility symbolAccessibility) { switch (symbolAccessibility) { case Accessibility.Private: return GetIconName(groupName, "Private"); case Accessibility.Protected: case Accessibility.ProtectedAndInternal: case Accessibility.ProtectedOrInternal: return GetIconName(groupName, "Protected"); case Accessibility.Internal: return GetIconName(groupName, "Internal"); case Accessibility.Public: case Accessibility.NotApplicable: return GetIconName(groupName, "Public"); default: throw new ArgumentException(); } } public static void Initialize(IGlyphService glyphService, IIconService iconService) { var supportedGlyphGroups = new Dictionary<StandardGlyphGroup, string> { { StandardGlyphGroup.GlyphGroupError, "Error" }, { StandardGlyphGroup.GlyphGroupDelegate, "Delegate" }, { StandardGlyphGroup.GlyphGroupEnum, "Enum" }, { StandardGlyphGroup.GlyphGroupStruct, "Struct" }, { StandardGlyphGroup.GlyphGroupClass, "Class" }, { StandardGlyphGroup.GlyphGroupInterface, "Interface" }, { StandardGlyphGroup.GlyphGroupModule, "Module" }, { StandardGlyphGroup.GlyphGroupConstant, "Constant" }, { StandardGlyphGroup.GlyphGroupEnumMember, "EnumMember" }, { StandardGlyphGroup.GlyphGroupEvent, "Event" }, { StandardGlyphGroup.GlyphExtensionMethodPrivate, "ExtensionMethodPrivate" }, { StandardGlyphGroup.GlyphExtensionMethodProtected, "ExtensionMethodProtected" }, { StandardGlyphGroup.GlyphExtensionMethodInternal, "ExtensionMethodInternal" }, { StandardGlyphGroup.GlyphExtensionMethod, "ExtensionMethod" }, { StandardGlyphGroup.GlyphGroupMethod, "Method" }, { StandardGlyphGroup.GlyphGroupProperty, "Property" }, { StandardGlyphGroup.GlyphGroupField, "Field" }, { StandardGlyphGroup.GlyphGroupOperator, "Operator" }, { StandardGlyphGroup.GlyphReference, "Reference" } }; var supportedGlyphItems = new Dictionary<StandardGlyphItem, string> { { StandardGlyphItem.GlyphItemPrivate, "Private" }, { StandardGlyphItem.GlyphItemProtected, "Protected" }, { StandardGlyphItem.GlyphItemInternal, "Internal" }, { StandardGlyphItem.GlyphItemPublic, "Public" }, { StandardGlyphItem.GlyphItemFriend, "Friend" } }; foreach (var groupKvp in supportedGlyphGroups) { foreach (var itemKvp in supportedGlyphItems) { var iconName = GetIconName(groupKvp.Value, itemKvp.Value); var localGroup = groupKvp.Key; var localItem = itemKvp.Key; iconService.AddIcon(iconName, iconName, () => glyphService.GetGlyph(localGroup, localItem)); } } } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/EditorFeatures/CSharpTest/ImplementAbstractClass/ImplementAbstractClassTests.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.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementAbstractClass { public partial class ImplementAbstractClassTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public ImplementAbstractClassTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpImplementAbstractClassCodeFixProvider()); private OptionsCollection AllOptionsOff => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, }; internal Task TestAllOptionsOffAsync( string initialMarkup, string expectedMarkup, int index = 0, OptionsCollection options = null, ParseOptions parseOptions = null) { options = options ?? new OptionsCollection(GetLanguage()); options.AddRange(AllOptionsOff); return TestInRegularAndScriptAsync( initialMarkup, expectedMarkup, index: index, options: options, parseOptions: parseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestSimpleMethods() { await TestAllOptionsOffAsync( @"abstract class Goo { protected abstract string GooMethod(); public abstract void Blah(); } abstract class Bar : Goo { public abstract bool BarMethod(); public override void Blah() { } } class [|Program|] : Goo { static void Main(string[] args) { } }", @"abstract class Goo { protected abstract string GooMethod(); public abstract void Blah(); } abstract class Bar : Goo { public abstract bool BarMethod(); public override void Blah() { } } class Program : Goo { static void Main(string[] args) { } public override void Blah() { throw new System.NotImplementedException(); } protected override string GooMethod() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [WorkItem(16434, "https://github.com/dotnet/roslyn/issues/16434")] public async Task TestMethodWithTupleNames() { await TestAllOptionsOffAsync( @"abstract class Base { protected abstract (int a, int b) Method((string, string d) x); } class [|Program|] : Base { }", @"abstract class Base { protected abstract (int a, int b) Method((string, string d) x); } class Program : Base { protected override (int a, int b) Method((string, string d) x) { throw new System.NotImplementedException(); } }"); } [WorkItem(543234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543234")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNotAvailableForStruct() { await TestMissingInRegularAndScriptAsync( @"abstract class Goo { public abstract void Bar(); } struct [|Program|] : Goo { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalIntParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(int x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(int x = 3); } class b : d { public override void goo(int x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalCharParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(char x = 'a'); } class [|b|] : d { }", @"abstract class d { public abstract void goo(char x = 'a'); } class b : d { public override void goo(char x = 'a') { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalStringParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(string x = ""x""); } class [|b|] : d { }", @"abstract class d { public abstract void goo(string x = ""x""); } class b : d { public override void goo(string x = ""x"") { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalShortParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(short x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(short x = 3); } class b : d { public override void goo(short x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalDecimalParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(decimal x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(decimal x = 3); } class b : d { public override void goo(decimal x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalDoubleParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(double x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(double x = 3); } class b : d { public override void goo(double x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalLongParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(long x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(long x = 3); } class b : d { public override void goo(long x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalFloatParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(float x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(float x = 3); } class b : d { public override void goo(float x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUshortParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(ushort x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(ushort x = 3); } class b : d { public override void goo(ushort x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUintParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(uint x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(uint x = 3); } class b : d { public override void goo(uint x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUlongParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(ulong x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(ulong x = 3); } class b : d { public override void goo(ulong x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalStructParameter_CSharp7() { await TestAllOptionsOffAsync( @"struct b { } abstract class d { public abstract void goo(b x = new b()); } class [|c|] : d { }", @"struct b { } abstract class d { public abstract void goo(b x = new b()); } class c : d { public override void goo(b x = default(b)) { throw new System.NotImplementedException(); } }", parseOptions: TestOptions.Regular7); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalStructParameter() { await TestAllOptionsOffAsync( @"struct b { } abstract class d { public abstract void goo(b x = new b()); } class [|c|] : d { }", @"struct b { } abstract class d { public abstract void goo(b x = new b()); } class c : d { public override void goo(b x = default) { throw new System.NotImplementedException(); } }"); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalNullableStructParameter() { await TestAllOptionsOffAsync( @"struct b { } abstract class d { public abstract void m(b? x = null, b? y = default(b?)); } class [|c|] : d { }", @"struct b { } abstract class d { public abstract void m(b? x = null, b? y = default(b?)); } class c : d { public override void m(b? x = null, b? y = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalNullableIntParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void m(int? x = 5, int? y = default(int?)); } class [|c|] : d { }", @"abstract class d { public abstract void m(int? x = 5, int? y = default(int?)); } class c : d { public override void m(int? x = 5, int? y = null) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalObjectParameter() { await TestAllOptionsOffAsync( @"class b { } abstract class d { public abstract void goo(b x = null); } class [|c|] : d { }", @"class b { } abstract class d { public abstract void goo(b x = null); } class c : d { public override void goo(b x = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(543883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543883")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestDifferentAccessorAccessibility() { await TestAllOptionsOffAsync( @"abstract class c1 { public abstract c1 this[c1 x] { get; internal set; } } class [|c2|] : c1 { }", @"abstract class c1 { public abstract c1 this[c1 x] { get; internal set; } } class c2 : c1 { public override c1 this[c1 x] { get { throw new System.NotImplementedException(); } internal set { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestEvent1() { await TestAllOptionsOffAsync( @"using System; abstract class C { public abstract event Action E; } class [|D|] : C { }", @"using System; abstract class C { public abstract event Action E; } class D : C { public override event Action E; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestIndexer1() { await TestAllOptionsOffAsync( @"using System; abstract class C { public abstract int this[string s] { get { } internal set { } } } class [|D|] : C { }", @"using System; abstract class C { public abstract int this[string s] { get { } internal set { } } } class D : C { public override int this[string s] { get { throw new NotImplementedException(); } internal set { throw new NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestMissingInHiddenType() { await TestMissingInRegularAndScriptAsync( @"using System; abstract class Goo { public abstract void F(); } class [|Program|] : Goo { #line hidden } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestGenerateIfLocationAvailable() { await TestAllOptionsOffAsync( @"#line default using System; abstract class Goo { public abstract void F(); } partial class [|Program|] : Goo { void Bar() { } #line hidden } #line default", @"#line default using System; abstract class Goo { public abstract void F(); } partial class Program : Goo { public override void F() { throw new NotImplementedException(); } void Bar() { } #line hidden } #line default"); } [WorkItem(545585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545585")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOnlyGenerateUnimplementedAccessors() { await TestAllOptionsOffAsync( @"using System; abstract class A { public abstract int X { get; set; } } abstract class B : A { public override int X { get { throw new NotImplementedException(); } } } class [|C|] : B { }", @"using System; abstract class A { public abstract int X { get; set; } } abstract class B : A { public override int X { get { throw new NotImplementedException(); } } } class C : B { public override int X { set { throw new NotImplementedException(); } } }"); } [WorkItem(545615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545615")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestParamsArray() { await TestAllOptionsOffAsync( @"class A { public virtual void Goo(int x, params int[] y) { } } abstract class B : A { public abstract override void Goo(int x, int[] y = null); } class [|C|] : B { }", @"class A { public virtual void Goo(int x, params int[] y) { } } abstract class B : A { public abstract override void Goo(int x, int[] y = null); } class C : B { public override void Goo(int x, params int[] y) { throw new System.NotImplementedException(); } }"); } [WorkItem(545636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545636")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullPointerType() { await TestAllOptionsOffAsync( @"abstract class C { unsafe public abstract void Goo(int* x = null); } class [|D|] : C { }", @"abstract class C { unsafe public abstract void Goo(int* x = null); } class D : C { public override unsafe void Goo(int* x = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(545637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545637")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestErrorTypeCalledVar() { await TestAllOptionsOffAsync( @"extern alias var; abstract class C { public abstract void Goo(var::X x); } class [|D|] : C { }", @"extern alias var; abstract class C { public abstract void Goo(var::X x); } class D : C { public override void Goo(X x) { throw new System.NotImplementedException(); } }"); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task Bugfix_581500() { await TestAllOptionsOffAsync( @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class [|T|] : A<T> { } } }", @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class T : A<T> { public override void M(B.T x) { throw new System.NotImplementedException(); } } } }"); } [WorkItem(625442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625442")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task Bugfix_625442() { await TestAllOptionsOffAsync( @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class [|T|] : A<B.T> { } } } ", @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class T : A<B.T> { public override void M(A<A<T>.B>.B.T x) { throw new System.NotImplementedException(); } } } } "); } [WorkItem(2407, "https://github.com/dotnet/roslyn/issues/2407")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task ImplementClassWithInaccessibleMembers() { await TestAllOptionsOffAsync( @"using System; using System.Globalization; public class [|x|] : EastAsianLunisolarCalendar { }", @"using System; using System.Globalization; public class x : EastAsianLunisolarCalendar { public override int[] Eras { get { throw new NotImplementedException(); } } internal override int MinCalendarYear { get { throw new NotImplementedException(); } } internal override int MaxCalendarYear { get { throw new NotImplementedException(); } } internal override EraInfo[] CalEraInfo { get { throw new NotImplementedException(); } } internal override DateTime MinDate { get { throw new NotImplementedException(); } } internal override DateTime MaxDate { get { throw new NotImplementedException(); } } public override int GetEra(DateTime time) { throw new NotImplementedException(); } internal override int GetGregorianYear(int year, int era) { throw new NotImplementedException(); } internal override int GetYear(int year, DateTime time) { throw new NotImplementedException(); } internal override int GetYearInfo(int LunarYear, int Index) { throw new NotImplementedException(); } }"); } [WorkItem(13149, "https://github.com/dotnet/roslyn/issues/13149")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestPartialClass1() { await TestAllOptionsOffAsync( @"using System; public abstract class Base { public abstract void Dispose(); } partial class [|A|] : Base { } partial class A { }", @"using System; public abstract class Base { public abstract void Dispose(); } partial class A : Base { public override void Dispose() { throw new NotImplementedException(); } } partial class A { }"); } [WorkItem(13149, "https://github.com/dotnet/roslyn/issues/13149")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestPartialClass2() { await TestAllOptionsOffAsync( @"using System; public abstract class Base { public abstract void Dispose(); } partial class [|A|] { } partial class A : Base { }", @"using System; public abstract class Base { public abstract void Dispose(); } partial class A { public override void Dispose() { throw new NotImplementedException(); } } partial class A : Base { }"); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Method1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract void M(int x); } class [|T|] : A { }", @"abstract class A { public abstract void M(int x); } class T : A { public override void M(int x) => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; } } class T : A { public override int M => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { set; } } class T : A { public override int M { set { throw new System.NotImplementedException(); } } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; set; } } class T : A { public override int M { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexers1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { get; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { get; } } class T : A { public override int this[int i] => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexer3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { set; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { set; } } class T : A { public override int this[int i] { set { throw new System.NotImplementedException(); } } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexer4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { get; set; } } class T : A { public override int this[int i] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; } } class T : A { public override int M { get => throw new System.NotImplementedException(); } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, }); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { set; } } class T : A { public override int M { set => throw new System.NotImplementedException(); } }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; set; } } class T : A { public override int M { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestWithGroupingOff1() { await TestInRegularAndScriptAsync( @"abstract class Base { public abstract int Prop { get; } } class [|Derived|] : Base { void Goo() { } }", @"abstract class Base { public abstract int Prop { get; } } class Derived : Base { void Goo() { } public override int Prop => throw new System.NotImplementedException(); }", options: Option(ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd)); } [WorkItem(17274, "https://github.com/dotnet/roslyn/issues/17274")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestAddedUsingWithBanner1() { await TestInRegularAndScriptAsync( @"// Copyright ... using Microsoft.Win32; namespace My { public abstract class Goo { public abstract void Bar(System.Collections.Generic.List<object> values); } public class [|Goo2|] : Goo // Implement Abstract Class { } }", @"// Copyright ... using System.Collections.Generic; using Microsoft.Win32; namespace My { public abstract class Goo { public abstract void Bar(System.Collections.Generic.List<object> values); } public class Goo2 : Goo // Implement Abstract Class { public override void Bar(List<object> values) { throw new System.NotImplementedException(); } } }"); } [WorkItem(17562, "https://github.com/dotnet/roslyn/issues/17562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullableOptionalParameters_CSharp7() { await TestInRegularAndScriptAsync( @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class [|D|] : B { }", @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class D : B { public override void M1(int i = 0, string s = null, int? j = null, V v = default(V)) { throw new System.NotImplementedException(); } public override void M2<T>(T? i = null) { throw new System.NotImplementedException(); } }", parseOptions: TestOptions.Regular7); } [WorkItem(17562, "https://github.com/dotnet/roslyn/issues/17562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullableOptionalParametersCSharp7() { await TestAsync( @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class [|D|] : B { }", @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class D : B { public override void M1(int i = 0, string s = null, int? j = null, V v = default(V)) { throw new System.NotImplementedException(); } public override void M2<T>(T? i = null) { throw new System.NotImplementedException(); } }", parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7)); } [WorkItem(17562, "https://github.com/dotnet/roslyn/issues/17562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullableOptionalParameters() { await TestInRegularAndScriptAsync( @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class [|D|] : B { }", @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class D : B { public override void M1(int i = 0, string s = null, int? j = null, V v = default) { throw new System.NotImplementedException(); } public override void M2<T>(T? i = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(13932, "https://github.com/dotnet/roslyn/issues/13932")] [WorkItem(5898, "https://github.com/dotnet/roslyn/issues/5898")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestAutoProperties() { await TestInRegularAndScript1Async( @"abstract class AbstractClass { public abstract int ReadOnlyProp { get; } public abstract int ReadWriteProp { get; set; } public abstract int WriteOnlyProp { set; } } class [|C|] : AbstractClass { }", @"abstract class AbstractClass { public abstract int ReadOnlyProp { get; } public abstract int ReadWriteProp { get; set; } public abstract int WriteOnlyProp { set; } } class C : AbstractClass { public override int ReadOnlyProp { get; } public override int ReadWriteProp { get; set; } public override int WriteOnlyProp { set => throw new System.NotImplementedException(); } }", parameters: new TestParameters(options: Option( ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestInWithMethod_Parameters() { await TestInRegularAndScriptAsync( @"abstract class TestParent { public abstract void Method(in int p); } public class [|Test|] : TestParent { }", @"abstract class TestParent { public abstract void Method(in int p); } public class Test : TestParent { public override void Method(in int p) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestRefReadOnlyWithMethod_ReturnType() { await TestInRegularAndScriptAsync( @"abstract class TestParent { public abstract ref readonly int Method(); } public class [|Test|] : TestParent { }", @"abstract class TestParent { public abstract ref readonly int Method(); } public class Test : TestParent { public override ref readonly int Method() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestRefReadOnlyWithProperty() { await TestInRegularAndScriptAsync( @"abstract class TestParent { public abstract ref readonly int Property { get; } } public class [|Test|] : TestParent { }", @"abstract class TestParent { public abstract ref readonly int Property { get; } } public class Test : TestParent { public override ref readonly int Property => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestInWithIndexer_Parameters() { await TestInRegularAndScriptAsync( @"abstract class TestParent { public abstract int this[in int p] { set; } } public class [|Test|] : TestParent { }", @"abstract class TestParent { public abstract int this[in int p] { set; } } public class Test : TestParent { public override int this[in int p] { set => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestRefReadOnlyWithIndexer_ReturnType() { await TestInRegularAndScriptAsync( @"abstract class TestParent { public abstract ref readonly int this[int p] { get; } } public class [|Test|] : TestParent { }", @"abstract class TestParent { public abstract ref readonly int this[int p] { get; } } public class Test : TestParent { public override ref readonly int this[int p] => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestUnmanagedConstraint() { await TestInRegularAndScriptAsync( @"public abstract class ParentTest { public abstract void M<T>() where T : unmanaged; } public class [|Test|] : ParentTest { }", @"public abstract class ParentTest { public abstract void M<T>() where T : unmanaged; } public class Test : ParentTest { public override void M<T>() { throw new System.NotImplementedException(); } }"); } [Fact] public async Task NothingOfferedWhenInheritanceIsPreventedByInternalAbstractMember() { await TestMissingAsync( @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class Base { internal abstract void Method(); } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class [|Derived|] : Base { Base inner; } </Document> </Project> </Workspace>"); } [WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestWithIncompleteGenericInBaseList() { await TestAllOptionsOffAsync( @"abstract class A<T> { public abstract void AbstractMethod(); } class [|B|] : A<int { }", @"abstract class A<T> { public abstract void AbstractMethod(); } class B : A<int { public override void AbstractMethod() { throw new System.NotImplementedException(); } }"); } [WorkItem(44907, "https://github.com/dotnet/roslyn/issues/44907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestWithRecords() { await TestAllOptionsOffAsync( @"abstract record A { public abstract void AbstractMethod(); } record [|B|] : A { }", @"abstract record A { public abstract void AbstractMethod(); } record B : A { public override void AbstractMethod() { throw new System.NotImplementedException(); } }", parseOptions: TestOptions.RegularPreview); } [WorkItem(44907, "https://github.com/dotnet/roslyn/issues/44907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestWithRecordsWithPositionalMembers() { await TestAllOptionsOffAsync( @"abstract record A { public abstract void AbstractMethod(); } record [|B|](int i) : A { }", @"abstract record A { public abstract void AbstractMethod(); } record B(int i) : A { public override void AbstractMethod() { throw new System.NotImplementedException(); } }", parseOptions: TestOptions.RegularPreview); } [WorkItem(48742, "https://github.com/dotnet/roslyn/issues/48742")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestUnconstrainedGenericNullable() { await TestAllOptionsOffAsync( @"#nullable enable abstract class B<T> { public abstract T? M(); } class [|D|] : B<int> { }", @"#nullable enable abstract class B<T> { public abstract T? M(); } class D : B<int> { public override int M() { throw new System.NotImplementedException(); } }"); } [WorkItem(48742, "https://github.com/dotnet/roslyn/issues/48742")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestUnconstrainedGenericNullable2() { await TestAllOptionsOffAsync( @"#nullable enable abstract class B<T> { public abstract T? M(); } class [|D<T>|] : B<T> where T : struct { }", @"#nullable enable abstract class B<T> { public abstract T? M(); } class D<T> : B<T> where T : struct { public override T M() { throw new System.NotImplementedException(); } }"); } [WorkItem(48742, "https://github.com/dotnet/roslyn/issues/48742")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestUnconstrainedGenericNullable_Tuple() { await TestAllOptionsOffAsync( @"#nullable enable abstract class B<T> { public abstract T? M(); } class [|D<T>|] : B<(T, T)> { }", @"#nullable enable abstract class B<T> { public abstract T? M(); } class D<T> : B<(T, T)> { public override (T, T) M() { throw new System.NotImplementedException(); } }"); } [WorkItem(48742, "https://github.com/dotnet/roslyn/issues/48742")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [InlineData("", "T")] [InlineData(" where T : class", "T")] [InlineData("", "T?")] [InlineData(" where T : class", "T?")] [InlineData(" where T : struct", "T?")] public async Task TestUnconstrainedGenericNullable_NoRegression(string constraint, string passToBase) { await TestAllOptionsOffAsync( $@"#nullable enable abstract class B<T> {{ public abstract T? M(); }} class [|D<T>|] : B<{passToBase}>{constraint} {{ }}", $@"#nullable enable abstract class B<T> {{ public abstract T? M(); }} class D<T> : B<{passToBase}>{constraint} {{ public override T? M() {{ throw new System.NotImplementedException(); }} }}"); } } }
// Licensed to the .NET Foundation under one or more 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.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ImplementAbstractClass; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementAbstractClass { public partial class ImplementAbstractClassTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public ImplementAbstractClassTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpImplementAbstractClassCodeFixProvider()); private OptionsCollection AllOptionsOff => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, }; internal Task TestAllOptionsOffAsync( string initialMarkup, string expectedMarkup, int index = 0, OptionsCollection options = null, ParseOptions parseOptions = null) { options = options ?? new OptionsCollection(GetLanguage()); options.AddRange(AllOptionsOff); return TestInRegularAndScriptAsync( initialMarkup, expectedMarkup, index: index, options: options, parseOptions: parseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestSimpleMethods() { await TestAllOptionsOffAsync( @"abstract class Goo { protected abstract string GooMethod(); public abstract void Blah(); } abstract class Bar : Goo { public abstract bool BarMethod(); public override void Blah() { } } class [|Program|] : Goo { static void Main(string[] args) { } }", @"abstract class Goo { protected abstract string GooMethod(); public abstract void Blah(); } abstract class Bar : Goo { public abstract bool BarMethod(); public override void Blah() { } } class Program : Goo { static void Main(string[] args) { } public override void Blah() { throw new System.NotImplementedException(); } protected override string GooMethod() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [WorkItem(16434, "https://github.com/dotnet/roslyn/issues/16434")] public async Task TestMethodWithTupleNames() { await TestAllOptionsOffAsync( @"abstract class Base { protected abstract (int a, int b) Method((string, string d) x); } class [|Program|] : Base { }", @"abstract class Base { protected abstract (int a, int b) Method((string, string d) x); } class Program : Base { protected override (int a, int b) Method((string, string d) x) { throw new System.NotImplementedException(); } }"); } [WorkItem(543234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543234")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNotAvailableForStruct() { await TestMissingInRegularAndScriptAsync( @"abstract class Goo { public abstract void Bar(); } struct [|Program|] : Goo { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalIntParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(int x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(int x = 3); } class b : d { public override void goo(int x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalCharParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(char x = 'a'); } class [|b|] : d { }", @"abstract class d { public abstract void goo(char x = 'a'); } class b : d { public override void goo(char x = 'a') { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalStringParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(string x = ""x""); } class [|b|] : d { }", @"abstract class d { public abstract void goo(string x = ""x""); } class b : d { public override void goo(string x = ""x"") { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalShortParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(short x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(short x = 3); } class b : d { public override void goo(short x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalDecimalParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(decimal x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(decimal x = 3); } class b : d { public override void goo(decimal x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalDoubleParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(double x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(double x = 3); } class b : d { public override void goo(double x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalLongParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(long x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(long x = 3); } class b : d { public override void goo(long x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalFloatParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(float x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(float x = 3); } class b : d { public override void goo(float x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUshortParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(ushort x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(ushort x = 3); } class b : d { public override void goo(ushort x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUintParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(uint x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(uint x = 3); } class b : d { public override void goo(uint x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalUlongParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void goo(ulong x = 3); } class [|b|] : d { }", @"abstract class d { public abstract void goo(ulong x = 3); } class b : d { public override void goo(ulong x = 3) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalStructParameter_CSharp7() { await TestAllOptionsOffAsync( @"struct b { } abstract class d { public abstract void goo(b x = new b()); } class [|c|] : d { }", @"struct b { } abstract class d { public abstract void goo(b x = new b()); } class c : d { public override void goo(b x = default(b)) { throw new System.NotImplementedException(); } }", parseOptions: TestOptions.Regular7); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalStructParameter() { await TestAllOptionsOffAsync( @"struct b { } abstract class d { public abstract void goo(b x = new b()); } class [|c|] : d { }", @"struct b { } abstract class d { public abstract void goo(b x = new b()); } class c : d { public override void goo(b x = default) { throw new System.NotImplementedException(); } }"); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalNullableStructParameter() { await TestAllOptionsOffAsync( @"struct b { } abstract class d { public abstract void m(b? x = null, b? y = default(b?)); } class [|c|] : d { }", @"struct b { } abstract class d { public abstract void m(b? x = null, b? y = default(b?)); } class c : d { public override void m(b? x = null, b? y = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalNullableIntParameter() { await TestAllOptionsOffAsync( @"abstract class d { public abstract void m(int? x = 5, int? y = default(int?)); } class [|c|] : d { }", @"abstract class d { public abstract void m(int? x = 5, int? y = default(int?)); } class c : d { public override void m(int? x = 5, int? y = null) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOptionalObjectParameter() { await TestAllOptionsOffAsync( @"class b { } abstract class d { public abstract void goo(b x = null); } class [|c|] : d { }", @"class b { } abstract class d { public abstract void goo(b x = null); } class c : d { public override void goo(b x = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(543883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543883")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestDifferentAccessorAccessibility() { await TestAllOptionsOffAsync( @"abstract class c1 { public abstract c1 this[c1 x] { get; internal set; } } class [|c2|] : c1 { }", @"abstract class c1 { public abstract c1 this[c1 x] { get; internal set; } } class c2 : c1 { public override c1 this[c1 x] { get { throw new System.NotImplementedException(); } internal set { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestEvent1() { await TestAllOptionsOffAsync( @"using System; abstract class C { public abstract event Action E; } class [|D|] : C { }", @"using System; abstract class C { public abstract event Action E; } class D : C { public override event Action E; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestIndexer1() { await TestAllOptionsOffAsync( @"using System; abstract class C { public abstract int this[string s] { get { } internal set { } } } class [|D|] : C { }", @"using System; abstract class C { public abstract int this[string s] { get { } internal set { } } } class D : C { public override int this[string s] { get { throw new NotImplementedException(); } internal set { throw new NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestMissingInHiddenType() { await TestMissingInRegularAndScriptAsync( @"using System; abstract class Goo { public abstract void F(); } class [|Program|] : Goo { #line hidden } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestGenerateIfLocationAvailable() { await TestAllOptionsOffAsync( @"#line default using System; abstract class Goo { public abstract void F(); } partial class [|Program|] : Goo { void Bar() { } #line hidden } #line default", @"#line default using System; abstract class Goo { public abstract void F(); } partial class Program : Goo { public override void F() { throw new NotImplementedException(); } void Bar() { } #line hidden } #line default"); } [WorkItem(545585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545585")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestOnlyGenerateUnimplementedAccessors() { await TestAllOptionsOffAsync( @"using System; abstract class A { public abstract int X { get; set; } } abstract class B : A { public override int X { get { throw new NotImplementedException(); } } } class [|C|] : B { }", @"using System; abstract class A { public abstract int X { get; set; } } abstract class B : A { public override int X { get { throw new NotImplementedException(); } } } class C : B { public override int X { set { throw new NotImplementedException(); } } }"); } [WorkItem(545615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545615")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestParamsArray() { await TestAllOptionsOffAsync( @"class A { public virtual void Goo(int x, params int[] y) { } } abstract class B : A { public abstract override void Goo(int x, int[] y = null); } class [|C|] : B { }", @"class A { public virtual void Goo(int x, params int[] y) { } } abstract class B : A { public abstract override void Goo(int x, int[] y = null); } class C : B { public override void Goo(int x, params int[] y) { throw new System.NotImplementedException(); } }"); } [WorkItem(545636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545636")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullPointerType() { await TestAllOptionsOffAsync( @"abstract class C { unsafe public abstract void Goo(int* x = null); } class [|D|] : C { }", @"abstract class C { unsafe public abstract void Goo(int* x = null); } class D : C { public override unsafe void Goo(int* x = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(545637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545637")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestErrorTypeCalledVar() { await TestAllOptionsOffAsync( @"extern alias var; abstract class C { public abstract void Goo(var::X x); } class [|D|] : C { }", @"extern alias var; abstract class C { public abstract void Goo(var::X x); } class D : C { public override void Goo(X x) { throw new System.NotImplementedException(); } }"); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task Bugfix_581500() { await TestAllOptionsOffAsync( @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class [|T|] : A<T> { } } }", @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class T : A<T> { public override void M(B.T x) { throw new System.NotImplementedException(); } } } }"); } [WorkItem(625442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625442")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task Bugfix_625442() { await TestAllOptionsOffAsync( @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class [|T|] : A<B.T> { } } } ", @"abstract class A<T> { public abstract void M(T x); abstract class B : A<B> { class T : A<B.T> { public override void M(A<A<T>.B>.B.T x) { throw new System.NotImplementedException(); } } } } "); } [WorkItem(2407, "https://github.com/dotnet/roslyn/issues/2407")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task ImplementClassWithInaccessibleMembers() { await TestAllOptionsOffAsync( @"using System; using System.Globalization; public class [|x|] : EastAsianLunisolarCalendar { }", @"using System; using System.Globalization; public class x : EastAsianLunisolarCalendar { public override int[] Eras { get { throw new NotImplementedException(); } } internal override int MinCalendarYear { get { throw new NotImplementedException(); } } internal override int MaxCalendarYear { get { throw new NotImplementedException(); } } internal override EraInfo[] CalEraInfo { get { throw new NotImplementedException(); } } internal override DateTime MinDate { get { throw new NotImplementedException(); } } internal override DateTime MaxDate { get { throw new NotImplementedException(); } } public override int GetEra(DateTime time) { throw new NotImplementedException(); } internal override int GetGregorianYear(int year, int era) { throw new NotImplementedException(); } internal override int GetYear(int year, DateTime time) { throw new NotImplementedException(); } internal override int GetYearInfo(int LunarYear, int Index) { throw new NotImplementedException(); } }"); } [WorkItem(13149, "https://github.com/dotnet/roslyn/issues/13149")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestPartialClass1() { await TestAllOptionsOffAsync( @"using System; public abstract class Base { public abstract void Dispose(); } partial class [|A|] : Base { } partial class A { }", @"using System; public abstract class Base { public abstract void Dispose(); } partial class A : Base { public override void Dispose() { throw new NotImplementedException(); } } partial class A { }"); } [WorkItem(13149, "https://github.com/dotnet/roslyn/issues/13149")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestPartialClass2() { await TestAllOptionsOffAsync( @"using System; public abstract class Base { public abstract void Dispose(); } partial class [|A|] { } partial class A : Base { }", @"using System; public abstract class Base { public abstract void Dispose(); } partial class A { public override void Dispose() { throw new NotImplementedException(); } } partial class A : Base { }"); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Method1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract void M(int x); } class [|T|] : A { }", @"abstract class A { public abstract void M(int x); } class T : A { public override void M(int x) => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; } } class T : A { public override int M => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { set; } } class T : A { public override int M { set { throw new System.NotImplementedException(); } } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Property4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; set; } } class T : A { public override int M { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexers1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { get; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { get; } } class T : A { public override int this[int i] => throw new System.NotImplementedException(); }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexer3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { set; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { set; } } class T : A { public override int this[int i] { set { throw new System.NotImplementedException(); } } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Indexer4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int this[int i] { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int this[int i] { get; set; } } class T : A { public override int this[int i] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never, NotificationOption2.Silent }, }); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor1() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; } } class T : A { public override int M { get => throw new System.NotImplementedException(); } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never, NotificationOption2.Silent }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible, NotificationOption2.Silent }, }); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor3() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { set; } } class T : A { public override int M { set => throw new System.NotImplementedException(); } }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); } [WorkItem(581500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/581500")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestCodeStyle_Accessor4() { await TestInRegularAndScriptAsync( @"abstract class A { public abstract int M { get; set; } } class [|T|] : A { }", @"abstract class A { public abstract int M { get; set; } } class T : A { public override int M { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } }", options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement)); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestWithGroupingOff1() { await TestInRegularAndScriptAsync( @"abstract class Base { public abstract int Prop { get; } } class [|Derived|] : Base { void Goo() { } }", @"abstract class Base { public abstract int Prop { get; } } class Derived : Base { void Goo() { } public override int Prop => throw new System.NotImplementedException(); }", options: Option(ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd)); } [WorkItem(17274, "https://github.com/dotnet/roslyn/issues/17274")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestAddedUsingWithBanner1() { await TestInRegularAndScriptAsync( @"// Copyright ... using Microsoft.Win32; namespace My { public abstract class Goo { public abstract void Bar(System.Collections.Generic.List<object> values); } public class [|Goo2|] : Goo // Implement Abstract Class { } }", @"// Copyright ... using System.Collections.Generic; using Microsoft.Win32; namespace My { public abstract class Goo { public abstract void Bar(System.Collections.Generic.List<object> values); } public class Goo2 : Goo // Implement Abstract Class { public override void Bar(List<object> values) { throw new System.NotImplementedException(); } } }"); } [WorkItem(17562, "https://github.com/dotnet/roslyn/issues/17562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullableOptionalParameters_CSharp7() { await TestInRegularAndScriptAsync( @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class [|D|] : B { }", @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class D : B { public override void M1(int i = 0, string s = null, int? j = null, V v = default(V)) { throw new System.NotImplementedException(); } public override void M2<T>(T? i = null) { throw new System.NotImplementedException(); } }", parseOptions: TestOptions.Regular7); } [WorkItem(17562, "https://github.com/dotnet/roslyn/issues/17562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullableOptionalParametersCSharp7() { await TestAsync( @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class [|D|] : B { }", @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class D : B { public override void M1(int i = 0, string s = null, int? j = null, V v = default(V)) { throw new System.NotImplementedException(); } public override void M2<T>(T? i = null) { throw new System.NotImplementedException(); } }", parseOptions: new CSharpParseOptions(LanguageVersion.CSharp7)); } [WorkItem(17562, "https://github.com/dotnet/roslyn/issues/17562")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestNullableOptionalParameters() { await TestInRegularAndScriptAsync( @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class [|D|] : B { }", @"struct V { } abstract class B { public abstract void M1(int i = 0, string s = null, int? j = null, V v = default(V)); public abstract void M2<T>(T? i = null) where T : struct; } sealed class D : B { public override void M1(int i = 0, string s = null, int? j = null, V v = default) { throw new System.NotImplementedException(); } public override void M2<T>(T? i = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(13932, "https://github.com/dotnet/roslyn/issues/13932")] [WorkItem(5898, "https://github.com/dotnet/roslyn/issues/5898")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestAutoProperties() { await TestInRegularAndScript1Async( @"abstract class AbstractClass { public abstract int ReadOnlyProp { get; } public abstract int ReadWriteProp { get; set; } public abstract int WriteOnlyProp { set; } } class [|C|] : AbstractClass { }", @"abstract class AbstractClass { public abstract int ReadOnlyProp { get; } public abstract int ReadWriteProp { get; set; } public abstract int WriteOnlyProp { set; } } class C : AbstractClass { public override int ReadOnlyProp { get; } public override int ReadWriteProp { get; set; } public override int WriteOnlyProp { set => throw new System.NotImplementedException(); } }", parameters: new TestParameters(options: Option( ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestInWithMethod_Parameters() { await TestInRegularAndScriptAsync( @"abstract class TestParent { public abstract void Method(in int p); } public class [|Test|] : TestParent { }", @"abstract class TestParent { public abstract void Method(in int p); } public class Test : TestParent { public override void Method(in int p) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestRefReadOnlyWithMethod_ReturnType() { await TestInRegularAndScriptAsync( @"abstract class TestParent { public abstract ref readonly int Method(); } public class [|Test|] : TestParent { }", @"abstract class TestParent { public abstract ref readonly int Method(); } public class Test : TestParent { public override ref readonly int Method() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestRefReadOnlyWithProperty() { await TestInRegularAndScriptAsync( @"abstract class TestParent { public abstract ref readonly int Property { get; } } public class [|Test|] : TestParent { }", @"abstract class TestParent { public abstract ref readonly int Property { get; } } public class Test : TestParent { public override ref readonly int Property => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestInWithIndexer_Parameters() { await TestInRegularAndScriptAsync( @"abstract class TestParent { public abstract int this[in int p] { set; } } public class [|Test|] : TestParent { }", @"abstract class TestParent { public abstract int this[in int p] { set; } } public class Test : TestParent { public override int this[in int p] { set => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestRefReadOnlyWithIndexer_ReturnType() { await TestInRegularAndScriptAsync( @"abstract class TestParent { public abstract ref readonly int this[int p] { get; } } public class [|Test|] : TestParent { }", @"abstract class TestParent { public abstract ref readonly int this[int p] { get; } } public class Test : TestParent { public override ref readonly int this[int p] => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestUnmanagedConstraint() { await TestInRegularAndScriptAsync( @"public abstract class ParentTest { public abstract void M<T>() where T : unmanaged; } public class [|Test|] : ParentTest { }", @"public abstract class ParentTest { public abstract void M<T>() where T : unmanaged; } public class Test : ParentTest { public override void M<T>() { throw new System.NotImplementedException(); } }"); } [Fact] public async Task NothingOfferedWhenInheritanceIsPreventedByInternalAbstractMember() { await TestMissingAsync( @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> public abstract class Base { internal abstract void Method(); } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class [|Derived|] : Base { Base inner; } </Document> </Project> </Workspace>"); } [WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestWithIncompleteGenericInBaseList() { await TestAllOptionsOffAsync( @"abstract class A<T> { public abstract void AbstractMethod(); } class [|B|] : A<int { }", @"abstract class A<T> { public abstract void AbstractMethod(); } class B : A<int { public override void AbstractMethod() { throw new System.NotImplementedException(); } }"); } [WorkItem(44907, "https://github.com/dotnet/roslyn/issues/44907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestWithRecords() { await TestAllOptionsOffAsync( @"abstract record A { public abstract void AbstractMethod(); } record [|B|] : A { }", @"abstract record A { public abstract void AbstractMethod(); } record B : A { public override void AbstractMethod() { throw new System.NotImplementedException(); } }", parseOptions: TestOptions.RegularPreview); } [WorkItem(44907, "https://github.com/dotnet/roslyn/issues/44907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestWithRecordsWithPositionalMembers() { await TestAllOptionsOffAsync( @"abstract record A { public abstract void AbstractMethod(); } record [|B|](int i) : A { }", @"abstract record A { public abstract void AbstractMethod(); } record B(int i) : A { public override void AbstractMethod() { throw new System.NotImplementedException(); } }", parseOptions: TestOptions.RegularPreview); } [WorkItem(48742, "https://github.com/dotnet/roslyn/issues/48742")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestUnconstrainedGenericNullable() { await TestAllOptionsOffAsync( @"#nullable enable abstract class B<T> { public abstract T? M(); } class [|D|] : B<int> { }", @"#nullable enable abstract class B<T> { public abstract T? M(); } class D : B<int> { public override int M() { throw new System.NotImplementedException(); } }"); } [WorkItem(48742, "https://github.com/dotnet/roslyn/issues/48742")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestUnconstrainedGenericNullable2() { await TestAllOptionsOffAsync( @"#nullable enable abstract class B<T> { public abstract T? M(); } class [|D<T>|] : B<T> where T : struct { }", @"#nullable enable abstract class B<T> { public abstract T? M(); } class D<T> : B<T> where T : struct { public override T M() { throw new System.NotImplementedException(); } }"); } [WorkItem(48742, "https://github.com/dotnet/roslyn/issues/48742")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] public async Task TestUnconstrainedGenericNullable_Tuple() { await TestAllOptionsOffAsync( @"#nullable enable abstract class B<T> { public abstract T? M(); } class [|D<T>|] : B<(T, T)> { }", @"#nullable enable abstract class B<T> { public abstract T? M(); } class D<T> : B<(T, T)> { public override (T, T) M() { throw new System.NotImplementedException(); } }"); } [WorkItem(48742, "https://github.com/dotnet/roslyn/issues/48742")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)] [InlineData("", "T")] [InlineData(" where T : class", "T")] [InlineData("", "T?")] [InlineData(" where T : class", "T?")] [InlineData(" where T : struct", "T?")] public async Task TestUnconstrainedGenericNullable_NoRegression(string constraint, string passToBase) { await TestAllOptionsOffAsync( $@"#nullable enable abstract class B<T> {{ public abstract T? M(); }} class [|D<T>|] : B<{passToBase}>{constraint} {{ }}", $@"#nullable enable abstract class B<T> {{ public abstract T? M(); }} class D<T> : B<{passToBase}>{constraint} {{ public override T? M() {{ throw new System.NotImplementedException(); }} }}"); } } }
-1
dotnet/roslyn
55,071
Change default level to warning to avoid creating 100gb sized log files
The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
dibarbet
2021-07-23T03:52:23Z
2021-07-23T17:59:06Z
6bcb7b3819c56a9e492b4f7621a6449191021d32
a8d8606f812c649276f0acb5e7ae6afa2a906764
Change default level to warning to avoid creating 100gb sized log files. The real fix is on the LSP client side to recycle live logs (while VS is open). That is tracked here for next sprint - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/ (I would consider this a blocker for fully enabling lsp pull diagnostics) However to avoid destroying my VS if I leave it on with pull diagnostics for a couple hours, I'm changing the default logging level. I also abstracted out the loghub log creation code into a mef service as part 1 of https://github.com/dotnet/roslyn/issues/55060 (vs lsp client will be re-used in VSMac, so we need to move the AbstractInProcLanguageClient code down to editor features)
./src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceService.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services. /// </summary> internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService)), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new EditAndContinueWorkspaceService(); } internal static readonly TraceLog Log = new(2048, "EnC"); private Func<Project, CompilationOutputs> _compilationOutputsProvider; /// <summary> /// List of active debugging sessions (small number of simoultaneously active sessions is expected). /// </summary> private readonly List<DebuggingSession> _debuggingSessions = new(); private static int s_debuggingSessionId; internal EditAndContinueWorkspaceService() { _compilationOutputsProvider = GetCompilationOutputs; } private static CompilationOutputs GetCompilationOutputs(Project project) { // The Project System doesn't always indicate whether we emit PDB, what kind of PDB we emit nor the path of the PDB. // To work around we look for the PDB on the path specified in the PDB debug directory. // https://github.com/dotnet/roslyn/issues/35065 return new CompilationOutputFilesWithImplicitPdbPath(project.CompilationOutputInfo.AssemblyPath); } private DebuggingSession? TryGetDebuggingSession(DebuggingSessionId sessionId) { lock (_debuggingSessions) { return _debuggingSessions.SingleOrDefault(s => s.Id == sessionId); } } private ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.ToImmutableArray(); } } private ImmutableArray<DebuggingSession> GetDiagnosticReportingDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.Where(s => s.ReportDiagnostics).ToImmutableArray(); } } public void OnSourceFileUpdated(Document document) { // notify all active debugging sessions foreach (var debuggingSession in GetActiveDebuggingSessions()) { // fire and forget _ = Task.Run(() => debuggingSession.OnSourceFileUpdatedAsync(document)).ReportNonFatalErrorAsync(); } } public async ValueTask<DebuggingSessionId> StartDebuggingSessionAsync( Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { Contract.ThrowIfTrue(captureAllMatchingDocuments && !captureMatchingDocuments.IsEmpty); IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates; if (captureAllMatchingDocuments || !captureMatchingDocuments.IsEmpty) { var documentsByProject = captureAllMatchingDocuments ? solution.Projects.Select(project => (project, project.State.DocumentStates.States.Values)) : GetDocumentStatesGroupedByProject(solution, captureMatchingDocuments); initialDocumentStates = await CommittedSolution.GetMatchingDocumentsAsync(documentsByProject, _compilationOutputsProvider, cancellationToken).ConfigureAwait(false); } else { initialDocumentStates = SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(); } var runtimeCapabilities = await debuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); var capabilities = ParseCapabilities(runtimeCapabilities); // For now, runtimes aren't returning capabilities, we just fall back to a known set. if (capabilities == EditAndContinueCapabilities.None) { capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddInstanceFieldToExistingType | EditAndContinueCapabilities.NewTypeDefinition; } var sessionId = new DebuggingSessionId(Interlocked.Increment(ref s_debuggingSessionId)); var session = new DebuggingSession(sessionId, solution, debuggerService, capabilities, _compilationOutputsProvider, initialDocumentStates, reportDiagnostics); lock (_debuggingSessions) { _debuggingSessions.Add(session); } return sessionId; } private static IEnumerable<(Project, IEnumerable<DocumentState>)> GetDocumentStatesGroupedByProject(Solution solution, ImmutableArray<DocumentId> documentIds) => from documentId in documentIds where solution.ContainsDocument(documentId) group documentId by documentId.ProjectId into projectDocumentIds let project = solution.GetRequiredProject(projectDocumentIds.Key) select (project, from documentId in projectDocumentIds select project.State.DocumentStates.GetState(documentId)); // internal for testing internal static EditAndContinueCapabilities ParseCapabilities(ImmutableArray<string> capabilities) { var caps = EditAndContinueCapabilities.None; foreach (var capability in capabilities) { caps |= capability switch { "Baseline" => EditAndContinueCapabilities.Baseline, "AddMethodToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType, "AddStaticFieldToExistingType" => EditAndContinueCapabilities.AddStaticFieldToExistingType, "AddInstanceFieldToExistingType" => EditAndContinueCapabilities.AddInstanceFieldToExistingType, "NewTypeDefinition" => EditAndContinueCapabilities.NewTypeDefinition, "ChangeCustomAttributes" => EditAndContinueCapabilities.ChangeCustomAttributes, // To make it eaiser for runtimes to specify more broad capabilities "AddDefinitionToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddInstanceFieldToExistingType, _ => EditAndContinueCapabilities.None }; } return caps; } public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { DebuggingSession? debuggingSession; lock (_debuggingSessions) { _debuggingSessions.TryRemoveFirst((s, sessionId) => s.Id == sessionId, sessionId, out debuggingSession); } Contract.ThrowIfNull(debuggingSession, "Debugging session has not started."); debuggingSession.EndSession(out documentsToReanalyze, out var telemetryData); } public void BreakStateEntered(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.BreakStateEntered(out documentsToReanalyze); } public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { return GetDiagnosticReportingDebuggingSessions().SelectManyAsArrayAsync( (s, arg, cancellationToken) => s.GetDocumentDiagnosticsAsync(arg.document, arg.activeStatementSpanProvider, cancellationToken), (document, activeStatementSpanProvider), cancellationToken); } /// <summary> /// Determine whether the updates made to projects containing the specified file (or all projects that are built, /// if <paramref name="sourceFilePath"/> is null) are ready to be applied and the debugger should attempt to apply /// them on "continue". /// </summary> /// <returns> /// Returns <see cref="ManagedModuleUpdateStatus.Blocked"/> if there are rude edits or other errors /// that block the application of the updates. Might return <see cref="ManagedModuleUpdateStatus.Ready"/> even if there are /// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until /// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts, /// but does not provide a definitive answer. Only <see cref="EmitSolutionUpdateAsync"/> can definitively determine whether /// the update is valid or not. /// </returns> public ValueTask<bool> HasChangesAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { // GetStatusAsync is called outside of edit session when the debugger is determining // whether a source file checksum matches the one in PDB. // The debugger expects no changes in this case. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.EditSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken); } public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(EmitSolutionUpdateResults.Empty); } return debuggingSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.CommitSolutionUpdate(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.DiscardSolutionUpdate(); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken); } public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); } return debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken); } public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<LinePositionSpan?>(null); } return debuggingSession.GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instructionId, cancellationToken); } public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<bool?>(null); } return debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId, cancellationToken); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly EditAndContinueWorkspaceService _service; public TestAccessor(EditAndContinueWorkspaceService service) { _service = service; } public void SetOutputProvider(Func<Project, CompilationOutputs> value) => _service._compilationOutputsProvider = value; public DebuggingSession GetDebuggingSession(DebuggingSessionId id) => _service.TryGetDebuggingSession(id) ?? throw ExceptionUtilities.UnexpectedValue(id); public ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() => _service.GetActiveDebuggingSessions(); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services. /// </summary> internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService { [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService)), Shared] private sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService? CreateService(HostWorkspaceServices workspaceServices) => new EditAndContinueWorkspaceService(); } internal static readonly TraceLog Log = new(2048, "EnC"); private Func<Project, CompilationOutputs> _compilationOutputsProvider; /// <summary> /// List of active debugging sessions (small number of simoultaneously active sessions is expected). /// </summary> private readonly List<DebuggingSession> _debuggingSessions = new(); private static int s_debuggingSessionId; internal EditAndContinueWorkspaceService() { _compilationOutputsProvider = GetCompilationOutputs; } private static CompilationOutputs GetCompilationOutputs(Project project) { // The Project System doesn't always indicate whether we emit PDB, what kind of PDB we emit nor the path of the PDB. // To work around we look for the PDB on the path specified in the PDB debug directory. // https://github.com/dotnet/roslyn/issues/35065 return new CompilationOutputFilesWithImplicitPdbPath(project.CompilationOutputInfo.AssemblyPath); } private DebuggingSession? TryGetDebuggingSession(DebuggingSessionId sessionId) { lock (_debuggingSessions) { return _debuggingSessions.SingleOrDefault(s => s.Id == sessionId); } } private ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.ToImmutableArray(); } } private ImmutableArray<DebuggingSession> GetDiagnosticReportingDebuggingSessions() { lock (_debuggingSessions) { return _debuggingSessions.Where(s => s.ReportDiagnostics).ToImmutableArray(); } } public void OnSourceFileUpdated(Document document) { // notify all active debugging sessions foreach (var debuggingSession in GetActiveDebuggingSessions()) { // fire and forget _ = Task.Run(() => debuggingSession.OnSourceFileUpdatedAsync(document)).ReportNonFatalErrorAsync(); } } public async ValueTask<DebuggingSessionId> StartDebuggingSessionAsync( Solution solution, IManagedEditAndContinueDebuggerService debuggerService, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken) { Contract.ThrowIfTrue(captureAllMatchingDocuments && !captureMatchingDocuments.IsEmpty); IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates; if (captureAllMatchingDocuments || !captureMatchingDocuments.IsEmpty) { var documentsByProject = captureAllMatchingDocuments ? solution.Projects.Select(project => (project, project.State.DocumentStates.States.Values)) : GetDocumentStatesGroupedByProject(solution, captureMatchingDocuments); initialDocumentStates = await CommittedSolution.GetMatchingDocumentsAsync(documentsByProject, _compilationOutputsProvider, cancellationToken).ConfigureAwait(false); } else { initialDocumentStates = SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(); } var runtimeCapabilities = await debuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); var capabilities = ParseCapabilities(runtimeCapabilities); // For now, runtimes aren't returning capabilities, we just fall back to a known set. if (capabilities == EditAndContinueCapabilities.None) { capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddInstanceFieldToExistingType | EditAndContinueCapabilities.NewTypeDefinition; } var sessionId = new DebuggingSessionId(Interlocked.Increment(ref s_debuggingSessionId)); var session = new DebuggingSession(sessionId, solution, debuggerService, capabilities, _compilationOutputsProvider, initialDocumentStates, reportDiagnostics); lock (_debuggingSessions) { _debuggingSessions.Add(session); } return sessionId; } private static IEnumerable<(Project, IEnumerable<DocumentState>)> GetDocumentStatesGroupedByProject(Solution solution, ImmutableArray<DocumentId> documentIds) => from documentId in documentIds where solution.ContainsDocument(documentId) group documentId by documentId.ProjectId into projectDocumentIds let project = solution.GetRequiredProject(projectDocumentIds.Key) select (project, from documentId in projectDocumentIds select project.State.DocumentStates.GetState(documentId)); // internal for testing internal static EditAndContinueCapabilities ParseCapabilities(ImmutableArray<string> capabilities) { var caps = EditAndContinueCapabilities.None; foreach (var capability in capabilities) { caps |= capability switch { "Baseline" => EditAndContinueCapabilities.Baseline, "AddMethodToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType, "AddStaticFieldToExistingType" => EditAndContinueCapabilities.AddStaticFieldToExistingType, "AddInstanceFieldToExistingType" => EditAndContinueCapabilities.AddInstanceFieldToExistingType, "NewTypeDefinition" => EditAndContinueCapabilities.NewTypeDefinition, "ChangeCustomAttributes" => EditAndContinueCapabilities.ChangeCustomAttributes, // To make it eaiser for runtimes to specify more broad capabilities "AddDefinitionToExistingType" => EditAndContinueCapabilities.AddMethodToExistingType | EditAndContinueCapabilities.AddStaticFieldToExistingType | EditAndContinueCapabilities.AddInstanceFieldToExistingType, _ => EditAndContinueCapabilities.None }; } return caps; } public void EndDebuggingSession(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { DebuggingSession? debuggingSession; lock (_debuggingSessions) { _debuggingSessions.TryRemoveFirst((s, sessionId) => s.Id == sessionId, sessionId, out debuggingSession); } Contract.ThrowIfNull(debuggingSession, "Debugging session has not started."); debuggingSession.EndSession(out documentsToReanalyze, out var telemetryData); } public void BreakStateEntered(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.BreakStateEntered(out documentsToReanalyze); } public ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { return GetDiagnosticReportingDebuggingSessions().SelectManyAsArrayAsync( (s, arg, cancellationToken) => s.GetDocumentDiagnosticsAsync(arg.document, arg.activeStatementSpanProvider, cancellationToken), (document, activeStatementSpanProvider), cancellationToken); } /// <summary> /// Determine whether the updates made to projects containing the specified file (or all projects that are built, /// if <paramref name="sourceFilePath"/> is null) are ready to be applied and the debugger should attempt to apply /// them on "continue". /// </summary> /// <returns> /// Returns <see cref="ManagedModuleUpdateStatus.Blocked"/> if there are rude edits or other errors /// that block the application of the updates. Might return <see cref="ManagedModuleUpdateStatus.Ready"/> even if there are /// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until /// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts, /// but does not provide a definitive answer. Only <see cref="EmitSolutionUpdateAsync"/> can definitively determine whether /// the update is valid or not. /// </returns> public ValueTask<bool> HasChangesAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { // GetStatusAsync is called outside of edit session when the debugger is determining // whether a source file checksum matches the one in PDB. // The debugger expects no changes in this case. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.EditSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken); } public ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(EmitSolutionUpdateResults.Empty); } return debuggingSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken); } public void CommitSolutionUpdate(DebuggingSessionId sessionId, out ImmutableArray<DocumentId> documentsToReanalyze) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.CommitSolutionUpdate(out documentsToReanalyze); } public void DiscardSolutionUpdate(DebuggingSessionId sessionId) { var debuggingSession = TryGetDebuggingSession(sessionId); Contract.ThrowIfNull(debuggingSession); debuggingSession.DiscardSolutionUpdate(); } public ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(DebuggingSessionId sessionId, Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return default; } return debuggingSession.GetBaseActiveStatementSpansAsync(solution, documentIds, cancellationToken); } public ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(DebuggingSessionId sessionId, TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); } return debuggingSession.GetAdjustedActiveStatementSpansAsync(mappedDocument, activeStatementSpanProvider, cancellationToken); } public ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(DebuggingSessionId sessionId, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<LinePositionSpan?>(null); } return debuggingSession.GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instructionId, cancellationToken); } public ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(DebuggingSessionId sessionId, Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { var debuggingSession = TryGetDebuggingSession(sessionId); if (debuggingSession == null) { return ValueTaskFactory.FromResult<bool?>(null); } return debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, instructionId, cancellationToken); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly EditAndContinueWorkspaceService _service; public TestAccessor(EditAndContinueWorkspaceService service) { _service = service; } public void SetOutputProvider(Func<Project, CompilationOutputs> value) => _service._compilationOutputsProvider = value; public DebuggingSession GetDebuggingSession(DebuggingSessionId id) => _service.TryGetDebuggingSession(id) ?? throw ExceptionUtilities.UnexpectedValue(id); public ImmutableArray<DebuggingSession> GetActiveDebuggingSessions() => _service.GetActiveDebuggingSessions(); } } }
-1